Longest Substring Without Repeating Characters

来源:互联网 发布:java 四行杨辉三角 编辑:程序博客网 时间:2024/04/29 01:04

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) {
        // Start typing your Java solution below
        // DO NOT write main() function
        Set<String> candidate = new HashSet<String>();
        int length = 0;
        
        for (int k=0; k<s.length();k++) {
            for (int i = k; i < s.length(); i++) {
                char tmp = s.charAt(i);
                if (candidate.contains(String.valueOf(tmp)) ) {
                    if (length < candidate.size()) {
                        length = candidate.size();    
                    }
                    candidate.clear();
                }
                candidate.add(String.valueOf(tmp));
            }
            if (length < candidate.size()) {
                length = candidate.size();    
            }
            candidate.clear();
        }




        return length;
    }
}
原创粉丝点击