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 subsequenceand not a substring.
看到这个问题第一反应是,设置两个指针(坐标)一个从字符串的头开始跑,与此嵌套一个for循环,从第二个位置开始遍历,并且不停的与第一个指针所指位置的字符进行比较。
然而这样的一个方法是比较愚笨的方法,甚至可以说是很暴力,所以可以考虑,如何去优雅又高效的节约时间呢。于是又想到了牺牲空间,节约时间的方式,具体实现源码如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
//考虑使用O(n)时间复杂度的算法来实现//
int left=0;
int result = 0;
int m[256]={0};
for(int i=0;i<s.size();i++){
if(m[s[i]]==0||m[s[i]]<left)
return result=max(result,i-left+1);
else
left=m[s[i]];
}
m[s[i]]=i+1;
}
return result;
};
//第一次实现的时候很蠢的使用了嵌套for循环来遍历数组,而没有考虑到//
//可以使用类似于hashmap的方式来节约时间//
浙公网安备 33010602011771号