仰望星空,脚踏实地。

Stay Foolish !Stay hungry !

【LeetCode】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.

Solution1

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        boolean []exist = new boolean[256];
        int i=0,maxLen = 0;
        for(int j=0;j<s.length();j++)
        {
            while(exist[s.charAt(j)])
            {
                exist[s.charAt(i)] = false;
                i++;
            }
            exist[s.charAt(j)]=true;
            maxLen = Math.max(j-i+1, maxLen);
            System.out.println();
        }
        return maxLen;
    }  
}

Solution2 HashMap

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int maxLen = 0;
        int availableFrom = 0;
        Map<Character,Integer> map = new HashMap<Character,Integer>();
        for(int j=0;j<s.length();j++)
        {
            if(map.containsKey(s.charAt(j)))
            {
                int last = map.get(s.charAt(j));
                availableFrom = Math.max(availableFrom, last+1);
            }
            maxLen = Math.max(maxLen, j-availableFrom+1);
            map.put(s.charAt(j), j);
        }
        return maxLen;
    }  
}
阅读更多
文章标签: hashmap
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

【LeetCode】3 Longest Substring Without Repeating Characters

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭