Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
翻译
给定一个字符串,找到最长的子串的长度,这个子串不存在重复的字符。
例如:
输入”abcabcbb”, 符合条件的子串就是”abc”, 长度为3。
输入”bbbbb”, 符合条件的子串就是”b”, 长度为1
输入”pwwkew”, 符合条件的子串就是”wke”, 长度为3。提示:要求必须是子串,例如”pwke” 是一个子序列但不是一个子串。
分析
先把给定的字符串进行处理,把字符串不存在重复的字符都找出来,放进map中,然后遍历找出最长的返回
代码:
1 class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 if(null!=s){ 4 5 char[] charArray=s.toCharArray(); 6 int len=0; 7 List<String> list = new ArrayList<String>(); 8 StringBuffer sb =new StringBuffer(); 9 for(int j=0;j<charArray.length;j++) { 10 11 for(int i=j;i<charArray.length;i++){ 12 if(1==charArray.length) { 13 list.add(String.valueOf(charArray[i])); 14 break; 15 } 16 if(sb.indexOf(String.valueOf(charArray[i]))<0){ 17 18 sb.append(String.valueOf(charArray[i])); 19 }else{ 20 list.add(sb.toString()); 21 22 sb.delete(0,sb.length()); 23 break; 24 } 25 } 26 } 27 28 for(int j=0;j<list.size();j++){ 29 if(list.get(j).length()>len){ 30 len=list.get(j).length(); 31 } 32 33 } 34 return len; 35 } 36 37 return 0; 38 39 } 40 }