給定一個字符串,找出不含有重復字符的最長子串的長度。
示例:
給定 "abcabcbb"
,沒有重復字符的最長子串是 "abc"
,那么長度就是3。
給定 "bbbbb"
,最長的子串就是 "b"
,長度是1。
給定 "pwwkew"
,最長子串是 "wke"
,長度是3。請注意答案必須是一個子串,"pwke"
是 子序列 而不是子串。
import java.util.LinkedList; class Solution { public int lengthOfLongestSubstring(String s) { int num=0;//記錄最長子串長度 int current=0;//記錄當前子串長度 char[] arr=s.toCharArray(); LinkedList<Character> temp=new LinkedList<>(); for (int i=0;i<arr.length ;i++ ) { if (!temp.contains(arr[i])) { temp.add(arr[i]); current=temp.size(); if (current>num) num=current; } else//如果新增字符與原子串中字符有重復的,刪除原子串中重復字符及在它之前的字符,與新增字符組成新的子串 { temp.add(arr[i]); int first=temp.indexOf(arr[i]); for (int j=0;j<first ;j++ ) temp.remove(); temp.remove(); } } return num; }
結果