LeetCode(java)3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

问题描述:在字符串中寻找最长的未存在重复字符的儿串长度;

本菜鸟的解法使用的HashMap用于查询之前是否已经出现过

public int lengthOfLongestSubstring(String s) {
    	char[] arr = s.toCharArray();
    	int max = 0;
    	int temp = 0;//用于存储出现重复字符后更改开始位置的长度
    	Integer preLocation;//用于存储map中put时返回的值:map返回的为与 key 关联的旧值;如果 key 没有任何映射关系,则返回 null。
     
    	HashMap<Character, Integer> map = new HashMap<Character, Integer>(s.length());//直接定义map的长度有利于减少扩容时间
     
    	for (int i = 0; i < arr.length; i++) {
    		preLocation = map.put(arr[i], i);//在map中查询该字符所处的位置
    		if(preLocation == null)//如果该字符仍然未出现过
    			temp++;//当前长度加1
    		else{
    			if(i-preLocation>temp)//如果该字符以及出现过,但是在新起点之前
    				temp++;//则认为该字符未出现过,长度继续加1
    			else//若该字符在新起点之后
    			{
        			max = Math.max(max, temp);//更新当前最长的长度
        			temp = i-preLocation;//更新字符串的新起点
    			}
    		}
    	}
    	max = Math.max(temp, max);//这句不可或缺,用于输入字符串未出现重复字符时
    	return max;
    }

时间复杂度为O(n); leetcode通过时间为11ms。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值