1. 程式人生 > >【LeetCode】3. Longest Substring Without Repeating Characters

【LeetCode】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.

思路

沒有重複字元的最長子串

使用map來儲存字串以及對應的索引,建立一張索引表。以起點start開始查詢,若無重複字元,則maxlen = i-start

abcabcbb
^  ^
s  i

當字元查表已存在,更新起點start為當前字元索引

Solution

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_map<char,int>
char_map; int maxlen= 0; int start = -1; for(int i = 0; i<s.length();i++){ if(char_map.count(s[i])!=0){ start = max(start,char_map[s[i]]); } char_map[s[i]]=i; maxlen = max(maxlen,i-start); } return
maxlen; } };