Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
思路:
max = 0
s = "abcabcbb";
sub = "";
1, sub = a; max = 1;
2, sub = ab; max = 2;
3, sub = abc; max = 3;
4, sub = bca; max = 3;
5, sub = cab; max = 3;
6, sub = abc; max = 3;
7, sub = cb;(因为abc中含有b,所以新的子串为原来子串b之后的字符串加上重复的那个字符,及取abc的c字符串加上重复的那个字符b,构成新的sub字符串cb) max = 3;
8, sub = b;(理由同上) max = 3;
1 class Solution 2 { 3 public: 4 int lengthOfLongestSubstring(string s) 5 { 6 int max = 0; 7 string sub = ""; 8 9 for(int i = 0; i < s.size(); i++) 10 { 11 if(string::npos == sub.find(s[i])) 12 sub += s[i]; 13 else 14 sub = sub.substr(sub.find(s[i]) + 1) + s[i]; 15 16 max = max >= sub.length() ? max : sub.length(); 17 } 18 return max; 19 } 20 };