3.Longest Substring Without Repeating Characters
题目描述
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
算法代码
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if( s.length() == 0){
return 0;
}
char charArr[s.length()];
strcpy(charArr, s.c_str());
int max = 0;
int begin = 0;
int end = 0;
bool flag = true;
for(int i = 1 ; i < s.length() ; i++){
flag = true;
for( int j = begin ; j <= end ; j++){
if( charArr[i] == charArr[j]){
end = begin + 1 ;
begin = begin + 1;
i = begin;
flag = false;
break;
}
}
if( flag ){
end++;
if( (end - begin) > max ){
max = end - begin;
}
}
}
return max + 1;
}
};
解题思路
- 个人采用的思路是先把string转换为char数组再判断,这样的话要对 s = ""; 做特殊判断,因为这样长度为 0 ,无法开辟数组
- 本算法的时间为 n^2 ,是从第一个字母开始向后寻找,直到找到一个不重复的字母,记录下来,然后再从第二个字母向后寻找,如此循环。