`
hcx2013
  • 浏览: 88724 次
社区版块
存档分类
最新评论

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.

 

 

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.equals("")) {
        	return 0;
        }
        int slow = 0;
        int fast = 0;
        int res = 0;
        HashSet<Character> hashSet = new HashSet<>();
        while (fast < s.length()) {
        	if (hashSet.contains(s.charAt(fast))) {
        		if (res < (fast-slow)) {
        			res = fast-slow;
        		}
        		while (s.charAt(slow) != s.charAt(fast)) {
        			hashSet.remove(s.charAt(slow));
        			slow++;
        		}
        		slow++;
        	} else {
        		hashSet.add(s.charAt(fast));
        	}
        	fast++;
        }
        res = Math.max(res, fast-slow);
        return res;
    }
}

 

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    if (s === undefined || s.length === 0) {
    	return 0;
    }
    var hash = new Array(256);
    for (var i = 0; i < 256; i++) {
    	hash[i] = -1;
    }
    var len = 0;
    var pre = -1;
    var cur = 0;
    for (i = 0; i != s.length; i++) {
    	pre = Math.max(pre, hash[s.charAt(i).charCodeAt()]);
    	cur = i - pre;
    	len = Math.max(cur, len);
    	hash[s.charAt(i).charCodeAt()] = i;
    }
    return len;
};

 

 

0
4
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics