3 Longest Substring Without Repeating Characters

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.

Solution:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.size();
        map<char, int> record;
        int istart = 0, max_len = 0;
        for ( int i = 0; i <= n-1; i++ ) {
            if ( record.find(s[i]) == record.end() ) { record[s[i]] = i; continue;}
            if ( record[s[i]] < istart ) {record[s[i]] = i; continue; }
            max_len = max(max_len, i - istart);
            istart = record[s[i]] + 1;
            record[s[i]] = i;
        }
        // note to consider n-istart
        return max(max_len, n-istart);
    }
};

Notes: operations of map

map<char, int> wordMap;
char c;
int i;
wordMap.insert(pair<char, int>(c, i));
auto it = wordMap.find(c)
int i = it->second;

Notes
没能一遍做对诶。主要两个问题:

  1. 当发现s[i]已经出现在map里,需要判断record[s[i]]是否大于i0。

    1. 如果小于,则没有关系,只需要更新record[s[i]]即可。)
    2. 如果大于,则计算当前长度,把istart更新为 record[s[i]]+1
  2. 注意最后一个长度也需要计算在内,所以返回max(max_len, n-istart)

results matching ""

    No results matching ""