[LeetCode] No.3 Longest Substring Without Repeating Characters

链接:

https://leetcode.com/problems/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.

分析:

这道题方式还是要使用双指针的方式,两个游标,同时维护一个集合,一个游标标注左侧index 一个游标标注右侧index,在两游标之间不能出现重复字符,当无重复的时候移动右侧游标,一旦移动到重复移动左侧游标,在此过程中记录最大长度。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
            int j = 0;
        int length = 0;
        if(s.equals("")) {
            return 0;
        }
        Map map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            while (j < s.length() && (map.get(s.charAt(j))==null || map.get(s.charAt(j)) == 0)) {
                map.put(s.charAt(j), 1);
                length = Math.max(j-i, length);
                j++;

            }
            map.put(s.charAt(i),0);
        }
        return length+1;
    }
}

你可能感兴趣的:([LeetCode] No.3 Longest Substring Without Repeating Characters)