1. 程式人生 > >3. Longest Substring Without Repeating Characters無重復字符的最長子串

3. Longest Substring Without Repeating Characters無重復字符的最長子串

clas public problem leet style 循環 重復字符 etc spa

網址:https://leetcode.com/problems/longest-substring-without-repeating-characters/

顯然采用sliding window滑動窗口法,輔助以哈希表,判斷字符是否已使用

  • 不斷擴充 j,直到 s[j] 已經使用
  • 此時,把 i 移動到 j 之前的 s[j] 字符前面,繼續循環
  • class Solution {
    public:
        int lengthOfLongestSubstring(string s)
        {
            int i = 0, j;
            int ans = 0;
            map
    <char, int> mp; for(j = 0; j<s.size(); j++) { if(mp.find(s[j]) == mp.end() || mp[s[j]] == 0) { mp[s[j]] = 1; } else { ans = max(ans,(j-i)); while(s[i] != s[j]) { mp[s[i]]
    = 0; i++; } i++; } } ans = max(ans,(j-i)); return ans; } };

    技術分享圖片

3. Longest Substring Without Repeating Characters無重復字符的最長子串