首页 > 代码库 > Longest Substring Without Repeating Characters
Longest Substring Without Repeating Characters
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。