LeetCode学习之路-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.

即求最长不重复子串。。。老生长谈的问题了
基本的思路是滑动窗口,不重复的窗口就放入map中,重复的就删除知道map中没有重复的值为止。在此过程中,时刻记录map中元素的数量。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char,int> hashMap;
        int i,j,ans = 0;
        for(i = 0,j = 0; i < s.size() && j < s.size();++j)
        {
            if(hashMap.count(s[j])) i = max(i,hashMap[s[j]]);
            ans = max(ans, j-i+1);
            hashMap[s[j]] = j+1;
        }
        return ans;
    }
};

你可能感兴趣的:(leetcode,leetcode)