問題描述
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.
思路描述
尋找字符串中最長的非重複字符的子串。思路:abcdefc,出現重複字符則截斷從重複字符後一個字符開始的子串“defc”繼續統計非重複字符子串,最終達到最長非重複字符子串!
代碼
class Solution {
public:
int lengthOfLongestSubstring(string s) {
string s1 ;
int ans=0;
int count=0;
int idx;
for (int i = 0; i < s.length(); i++)
{
if ((idx = s1.find(s[i], 0)) == string::npos)
{
s1 += s[i];
count++;
}
else
{
if (count>ans) ans = count;
s1 = s1.substr(idx + 1) + s[i];
count = s1.length();
}
}
return count > ans ? count : ans;
}
};