String_Longest Substring Without Repeating Characters

package leetCode;
import java.util.Map;
import java.util.HashMap;

public class longestNoRepeating {
	public int lengthOfLongestSubstring(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(s==null||s.length()<1)
        return 0;
        
        
        boolean[] table = new boolean[256];
        int max = 1;
        int current = 1;
        int j = 0;
        table[s.charAt(0)] = true;
        int i;
        for(i = 1 ; i < s.length();i++){
            
            
            if(table[s.charAt(i)] == true){
                
                current = i - j;
                max = Math.max(current,max);
                
                while(s.charAt(j)!=s.charAt(i)){
                    table[s.charAt(j)] = false;
                    j++;
                }
                j++;
                
                
                
                
            }else{
                table[s.charAt(i)] = true;
            }            
        }
        
        max = Math.max(i-j,max);
        
        return max;
        
    }



	public int longestSubstringWithoutRepeating(String s){
		Map<Character,Integer> map = new HashMap<Character,Integer>();
		
		int start = 0;
		int end = 0;
		int max = 1;
		
		while(end < s.length()){
			char cur = s.charAt(end);
			
			if(map.containsKey(cur) && map.get(cur)>= start){
				max = Math.max(max, end - start);
				start = map.get(cur)+1;
			}
			map.put(cur, end);
			end++;
			
		}
		return Math.max(end-start, max);
	}

}



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.


A very clever trick is to use HashMap to provide the current eligible character's position.

O(N)

Both are same in logic. But second is more elegant. Also, very import to check the last substring as it may be the longest

Second methods preferred.




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值