首页 > 其他 > 详细

3:Longest Substring Without Repeating Characters

时间:2015-03-25 23:29:09      阅读:215      评论:0      收藏:0      [点我收藏+]

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 LongestSubstringWithoutRepeatingCharacters {

     public int lengthOfLongestSubstring(String str) {
         Set<Character> sets = new HashSet<Character>();
        
         int max = 0;
        
         int start=0;
         for(int i=0,len=str.length();i<len;i++){
             char cha = str.charAt(i);
            
             if(sets.contains(cha)){
                 while(str.charAt(start)!=str.charAt(i)){
                     sets.remove(cha);
                     start++;
                 }
                
                 start++;
             }else{
                 sets.add(cha);
             }
             max=i-start>max?i-start:max;
             System.out.println(str.substring(start, i));
         }
        
         return max;
     }
    /**
     * @param args
     */
    public static void main(String[] args) {
        LongestSubstringWithoutRepeatingCharacters l = new LongestSubstringWithoutRepeatingCharacters();
        int len = l.lengthOfLongestSubstring("abcacddcefbb");
        System.out.println(len);
    }

}

 

使用集合Set不能包含重复元素的方法,从字符串的开始位置依次往后判断,如果存在重复元素,将子字符串的开始位置移动到重复元素位置再次判断。

3:Longest Substring Without Repeating Characters

原文:http://www.cnblogs.com/shisw/p/4367129.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!