Given a string, find the length of the longest substring without repeating characters.(給定一個字符串,找到最長的子串的長度,這個子串不存在重復的字符。 )
阿新 • • 發佈:2017-12-19
長度 index val color arraylist pub 翻譯 buffer int
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 = newArrayList<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 }
Given a string, find the length of the longest substring without repeating characters.(給定一個字符串,找到最長的子串的長度,這個子串不存在重復的字符。 )