码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Substring Without Repeating Characters

时间:2014-12-26 20:14:20      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

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.

开始想用穷举法,将所有的子串都遍历出来,结果超时了。

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         if(s.length() == 0){
 4             return 0;
 5         }
 6         if(s.length() == 1)
 7             return 1;
 8         int result = 1;
 9         for(int i = 0; i < s.length() - result; i++){
10             int j = i + 1;
11             for(; j < s.length(); j++){
12                 String sub = s.substring(i, j);
13                 if(-1 == sub.indexOf(s.charAt(j)))
14                 {
15                     if(sub.length() + 1 > result)
16                         result = sub.length() + 1;
17                     continue;
18                 }
19                 break;
20             }
21         }
22         
23         return result;
24     }
25 }

参考了别人的,只遍历字符串一遍,用hash表记录s.charAt(i)的位置。不断更新result,有点贪心算法的感觉,每次记录当前字符串的起始位置

参考的连接我懒得找就不贴出来了

import java.util.Hashtable;

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s.length() == 0){
            return 0;
        }
        if(s.length() == 1)
            return 1;
        int result = 0;                                        //最后返回的结果
        int index = -1;                                        //当前子串开始位置的前一个位置
        Hashtable<Character, Integer> map = new Hashtable<Character, Integer>();    //s[i]出现的位置
        
        for(int i = 0; i < s.length(); i++){
            Integer position = map.get(s.charAt(i));
            if(null != position && position > index)
                index = position;
            if(i - index > result)
                result = i - index;
            map.put(s.charAt(i), i);
        }
        
        return result;
    }
}

 

Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/luckygxf/p/4187456.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!