字符串-----最长不重复子字符串(leetcode3)

import java.util.HashMap;
public class Solution {
	public int lengthOfLongestSubstring(String s) {
		//记录最大长度
		int max=0;
		//left存放左边界
		int left=0;
		HashMap<Character, Integer> map=new HashMap<Character,Integer>();
		char[] ch=s.toCharArray();
		//循环遍历整个字符串
		for(int i=0;i<s.length();i++)
		{
			//判断第i个字符是否已经在map里
			if(map.containsKey(ch[i]))
			{
				//易错点 left不一定是map.get(ch[i])+1 因为left只能是越来越大 没有回头路 所以要与left作比较 取最大值
                left=Math.max(map.get(ch[i])+1, left);
				
			}
			//map 的键值对key存放字符 value存放字符对应的下标
            map.put(ch[i], i);
            //左边界和右边界确定长度
			max=Math.max(max, i-left+1);
		}
		return max;
	}
}

猜你喜欢

转载自blog.csdn.net/ustcyy91/article/details/80113282