求字符串中不重复的最长子串的长度

来源:互联网 发布:linux搭建java环境 编辑:程序博客网 时间:2024/06/06 00:08

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

描述:输入"abcabcbb", 输出 3(abc).输入 "bbbbb",输出1(b).输入 "pwwkew",输出3(wke)

1.使用hashmap解决:

public static int lengthOfLongestSubstring(String s) {        if(s.length()==0) return 0;        HashMap<Character,Integer> map = new HashMap<Character,Integer>();        int max = 0;        for(int right=0,left=0;right<s.length();right++){            if(map.containsKey(s.charAt(right))){            left = Math.max(left,map.get(s.charAt(right))+1);            }            map.put(s.charAt(right),right);            max = Math.max(max,right-left+1);        }        return max;    }

2.借用ASCII码表解决问题:

private static int lengthOfLongestSubstring_DP(String s) {int[] charIndex = new int[256];for (int i = 0; i < charIndex.length; i++) {charIndex[i] = -1;}int longest = 0,left = 0;for (int right = 0; right < s.length(); right++) {left = Math.max(charIndex[s.charAt(right)]+1,left);charIndex[s.charAt(right)] = right;longest = Math.max(longest,right-left+1);}return longest;}
上述两种方法的辅助的数据类型不同,但是解题思路是一致的,即通过寻找左右指针来确定最长不重复数组的长度。指针right一次往后遍历字符串,指针left但出现重复字符串时候往前移动到新的无重复字符的位置。

阅读全文
1 0