题目描述:
给定一个字符串,找出不含有重复字符的最长子串的长度。
示例:
给定"abcabcbb"
,没有重复字符的最长子串是"abc"
,那么长度就是3。
给定"bbbbb"
,最长的子串就是"b"
,长度是1。
给定"pwwkew"
,最长子串是"wke"
,长度是3。请注意答案必须是一个子串,"pwke"
是子序列而不是子串
解题思路:
设立左指针a和右指针b,
b指针向右侧伸缩{
对每个A[b]判断之前是否在之前的数组中出现过;
如果出现过,指针a指向出现过位置的下一个位置;
更新右指针和最大长度;
}
代码:
#include <stdio.h>#include <string>#include <stdlib.h>#include <algorithm>#include <iostream>using namespace std;class solution {public:int lengthOfLongestSubstring(string s) {int start(0), end(0), length(0),result(0);int Ssize = int(s.size());while (end < Ssize) {char tempChar = s[end];for (int index = start; index < end; index++) {//如果这个字符在数组中出现过,就让start 指向当前位置的下一位置,并更新长度if (tempChar == s[index]) {start = index + 1;length = end - start;break;}}end++;length++;result = max(result, length);}return result;}};int main() {string str = "abbbc";solution sol;int result = sol.lengthOfLongestSubstring(str);cout << result << endl;}
如果觉得《leetcode-无重复字符的最长子串》对你有帮助,请点赞、收藏,并留下你的观点哦!