longest substring without repeating letters

import java.util.HashSet;

/**
 * Created by chris on 2015/12/17.
 *  For example, the longest substring without repeating letters for "abcabcbb" is "abc",
 *  找出最长的没有重复字符的子串
 *  使用集合的方式
 */

public class LongestSubWithoutRepeatingChar {
    public int longestSubstrWithoutRepeatChar( String s){
        int start = 0;
        int end = 0;
        int Maxlength = 0;
        HashSet<Character> strPreSet = new HashSet<Character>();

        for (int i = 0; i < s.length(); i++) {
            int j=0;
            strPreSet.clear();
            for ( j = i; j < s.length(); j++) {
                //if (j >=s.length()) break;
                //if (s.charAt(j+1)-s.charAt(j) != 1) break;

                if(strPreSet.contains(s.charAt(j))){
                   break;
                }
                else {
                    strPreSet.add(s.charAt(j));
                }
            }

            if ((j - i) > Maxlength){
                start = i;
                end = j;
                Maxlength = j-i;
            }
        }
        return s.substring(start, end).length();
    }

}
Tagged on: ,

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>