[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<Character, Integer> 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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容