天天看點

leetcode-滑動視窗-3

import java.util.HashMap;

/**
<p>給定一個字元串 <code>s</code> ,請你找出其中不含有重複字元的 <strong>最長子串 </strong>的長度。</p>

<p> </p>

<p><strong>示例 1:</strong></p>

<pre>
<strong>輸入: </strong>s = "abcabcbb"
<strong>輸出: </strong>3 
<strong>解釋:</strong> 因為無重複字元的最長子串是 <code>"abc",是以其</code>長度為 3。
</pre>

<p><strong>示例 2:</strong></p>

<pre>
<strong>輸入: </strong>s = "bbbbb"
<strong>輸出: </strong>1
<strong>解釋: </strong>因為無重複字元的最長子串是 <code>"b"</code>,是以其長度為 1。
</pre>

<p><strong>示例 3:</strong></p>

<pre>
<strong>輸入: </strong>s = "pwwkew"
<strong>輸出: </strong>3
<strong>解釋: </strong>因為無重複字元的最長子串是 <code>"wke"</code>,是以其長度為 3。
     請注意,你的答案必須是 <strong>子串 </strong>的長度,<code>"pwke"</code> 是一個<em>子序列,</em>不是子串。
</pre>

<p> </p>

<p><strong>提示:</strong></p>

<ul>
    <li><code>0 <= s.length <= 5 * 10<sup>4</sup></code></li>
    <li><code>s</code> 由英文字母、數字、符号和空格組成</li>
</ul>
<div><div>Related Topics</div><div><li>哈希表</li><li>字元串</li><li>滑動視窗</li></div></div><br><div><li>👍 8088</li><li>👎 0</li></div>
*/

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int lengthOfLongestSubstring(String s) {
        //滑動視窗
        Map<Character,Integer> map = new HashMap<>();
        int max = 0;
        int left = 0;
        for (int i = 0; i < s.length(); i++) {
            if(map.containsKey(s.charAt(i))){
                left = Math.max(left,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-left+1);
        }
        return max;
    }
}
//leetcode submit region end(Prohibit modification and deletion)