LeetCode Longest Substring Without Repeating Characters

链接: https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/


字符串中最长连续不重复子序列,用JAVA中的哈希表比较方便

public class Solution {
    public int lengthOfLongestSubstring(String s) 
	{
		int n=s.length();
		int end=0;
		int start=0;
		int ans=0;
		HashMap<Character,Integer> map=new HashMap<Character,Integer>();
		while(end<n)
		{
			char c=s.charAt(end);
			Integer index=map.get(c);
			if(index!=null&&index>=start)			//发现重复元素
			{
				ans=Math.max(ans,end-start);
				start=index+1;
			}
			else
			{
				map.put(c, end);
				end++;
			}
		}
		if(end-start>ans)
		    ans=end-start;
		return ans;
		        
	}

}


原文地址:https://www.cnblogs.com/frankM/p/4399435.html