题目:
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.
思路:
题意就是给找到一个最长的没有重复字符的子串。我定义了一个bool数组用来表示对应的字符是否出现过。指针从左往右移动,如果遇到出现过的字符,就停止,跟当前max_length比较。清掉前面的字符串直至重复的字符,同时将bool数组更新。
代码:
1 class Solution 2 { 3 public: 4 int lengthOfLongestSubstring(string s) 5 { 6 int sz = s.size(); 7 bool occ[128] = {0}; 8 int result = 0; 9 int length = 0; 10 for(int i = 0; i < sz; i++) 11 { 12 int temp = (int)s[i]; 13 if(occ[temp]) 14 { 15 if(length > result) 16 { 17 result = length; 18 } 19 for(int j = i - length;j < i && (int)s[j] != temp;j++) 20 { 21 occ[(int)s[j]] = 0; 22 length--; 23 } 24 } 25 else 26 { 27 occ[temp] = 1; 28 length++; 29 } 30 } 31 if(length > result) 32 result = length; 33 return result; 34 } 35 };
参照leetcode上面的代码发现可以通过关闭输出流同步来减少运行时间:
1 static int close(){ 2 ios::sync_with_stdio(false); 3 cin.tie(0); 4 return 0; 5 }
leetcode上看到的另一种思路是这样子的: