题目描述
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.
题意:
就是寻找一个给定字符串中的不重复最长字串的长度。
比如abcdab,最长的串位abcd或cdab,长度位4.
哈希表方法:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++)
{
if (dict[s[i]] > start) //s[i]为字符,这里要转化为ASII码;
start = dict[s[i]]; //s[i]重复出现时,start值发生改变;
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
};
改良版的爆搜法:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n=s.size();
if(n==0) return 0;
if(n==1) return 1;
int moveindex=0;
int maxlen=0;
for(int i=1;i<n;i++)
{
for(int j=i-1;j>=moveindex;j--)//从i位置依次向前比较到moveindex;
{
if(s[i]==s[j])//相等,则移动moveindex到j+1;跳出循环;
{
moveindex=j+1;
break;
}
else
{
maxlen=max(maxlen,i-j+1);
}
}
}
return maxlen;
}
};