LeetCode学习之路-Longest Substring Without Repeating Characters

来源:互联网 发布:模拟投资基金软件 编辑:程序博客网 时间:2024/06/06 09:11

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;    }};
0 0
原创粉丝点击