Longest Substring Without Repeating Characters

205 篇文章 0 订阅
题目:

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.


最先想到的方法使用map存储字符和index信息,map中不存在字符,则put进来,存在

字符则统计map的size并和存储的最大长度比较,然后清空map。但当测试用例是一个

很长的String时,就会超时。

public static int lengthOfLongestSubstring(String s) {
		if(s==null)
			return 0;
		s=s.trim();
		int count=0;
		Map<Character,Integer> map=new HashMap<Character,Integer>();
		for(int i=0;i<s.length();i++){
			if(!map.containsKey(s.charAt(i)))
				map.put(s.charAt(i), i);
			else{
				count=Math.max(count, map.size());
				i=map.get(s.charAt(i));
				map.clear();
			}
		}
		return Math.max(count, map.size());
	}

改进的方法是用boolean数组存储字符信息,默认为false,数组中存在字符是,置为true,

否则,记录当前子字符串和count的最大值,将数组置为false,更新子字符串起始index。

public static int lengthOfLongestSubstring(String s){
		if(s==null||s.length()<=0)
			return 0;
		boolean[] ch=new boolean[128];
        int start = 0;
        int count = 0;
        for(int i=0;i<s.length();i++){
        	if(ch[s.charAt(i)]){//如果数组中不存在字符
        		count=Math.max(count, i-start);//比较子字符串长度和之前的长度记录
        		for (int k = start; k < i; k++) {
    				if (s.charAt(k)== s.charAt(i)) {
    					start = k + 1; //更新子字符串的起始位置
    					break;
    				}
    				ch[s.charAt(k)] = false;//将数组置为false
    			}
        	}else
        		ch[s.charAt(i)]=true;//将数组中字符对应的位置置为true
        }
        return Math.max(count, s.length()-start);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值