Wednesday, January 29, 2014

Code Exercises Round II: #4 in 8 days

problem: 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.

solution:
    public int lengthOfLongestSubstring(String s) {
        int maxCount = 0;
        
        for(int i = 0; i < s.length(); i++) {
            Set<Character> previous = new HashSet<Character>();
            int count = 0;
            for(int j = i; j < s.length(); j++) {
                if(previous.add(s.charAt(j))) {
                    count++;
                }
                else {
                    break;
                }
            }
            maxCount = Math.max(maxCount, count);
        }
        
        return maxCount;
    }

No comments:

Post a Comment