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.
网上广为流传的fa方法是用hashmap存储数据,虽然我第一感觉就是动态规划,大门时在空间和时间fu'z复杂度上面还是相差许多,所以接下来就要把这几行精简代码思想具体化
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)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
首先最好用现成的hashmap
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
感觉酷酷的,至于256,还不清楚, dict下标代表各种字符,而value是字符串的下标
思路是这样
从头kai'开始便利字符串,遇到字母,就把它的下标放进hashmap中,当我们遇到第一个重复的字符,由于这个字符是char c=s[i]在hashmap中对应的value不为-1,这个时候就找到了第一个重复位置,然后ba把这个重复位置记录下来并更新,如果以后遇到其他字符重复时候,那么长度就要从start和重复字符b位置中最大计算了,总之就是把重复位置找到,并更新。理解起来还是有点难度,hashmap用起来就很顺手了,
当我们遇到cho重复字符时,那么长度就要从shan上一个重复字符开始。这个感觉没有我的dp好用,理解起来有点费劲。