题目描述:
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.
本题给我们一个字符串,要我们返回最长的连续的没有重复字母的字符串的长度。
解题思路:
这题我的想法是把没有重复的字符串存储在一个临时字符串中。当碰到字符与临时字符串中的字符重复时,比较长度大小,删去重复字符之前的字符,继续存储。
第二个代码是我在参考LeetCode上优质解答后重新修改后的代码,思路是一样的,不过字符串的存储形式要比我的方法更高明一点,不用遍历存储的子字符串。是用字符作为下标,将字符在s中的位置存储到一个数组中,用一个数记录子字符串的开头。当遇到重复的字符时,只要让这个数等于前面那个相同字符的下标(下标要大于这个数)。只看文字说明很可能看不明白,只要代一个字符串进入函数中就能明白了。
我的代码:
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 int length=s.length(); 5 int result=0; 6 string temp=""; 7 for(int i=0;i<length;i++){ 8 for(int j=0;j<temp.length();j++){ 9 if(s[i]==temp[j]){ 10 result=max((int)temp.length(),result); 11 temp.erase(0,j+1); 12 } 13 } 14 temp+=s[i]; 15 } 16 result=max((int)temp.length(),result);//比较最后一个子字符串和先前答案长度大小 17 return result; 18 } 19 };
他人代码:
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 int length=s.length(); 5 int result=0,beg=-1; 6 vector<int> str(256,-1); 7 for(int i=0;i<length;i++){ 8 if(str[s[i]]!=-1) 9 beg=str[s[i]]>beg?str[s[i]]:beg; 10 str[s[i]]=i; 11 result=result>i-beg?result:i-beg; 12 } 13 return result; 14 } 15 };