leetcode No3. Longest Substring Without Repeating Characters

来源:互联网 发布:刘德华救歌迷知乎 编辑:程序博客网 时间:2024/06/07 17:48

Question:

Given a string, find the length of the longest substring without repeating characters.

Ex:

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.

Algorithm:Hash Table、Two Pointers

1、给出i,j分别表示不重复的开头和结尾,max_length记录最大长度,
2、j一直往右,同时用哈希表记录出现的字符,直到,有字符出现了两次,这时,i就应该到重复字符第一次出现的位置的下一位。
3、有字符出现两个次时,记录当前的子字符串长度cur_length,并和max_length作比较,如果比max_length大则更新。

Submitted Code:

class Solution {public:    int lengthOfLongestSubstring(string s) {        if(s.size()<2)return s.size();        int i=0;  //begin        int j=0;  //end        int cur_length=0;        int max_length=0;        map<char,int> hash;        while(j<s.size())        {            if(hash[s[j]]==0)            {                hash[s[j]]=1;                j++;            }            else             {                while(s[i]!=s[j])                {                    hash[s[i]]=0;                    i++;                }                i++;                j++;            }            cur_length = j-i;            max_length = max_length>cur_length?max_length:cur_length;        }        return max_length;    }};



0 0