Longest Substring Without Repeating Characters (leetcode3)
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 asubstring
"pwke"
is a
subsequence and not a substring.
複雜度為O(n^2)的思路就是判斷每一個子串是否有相同的字元,若沒有則記錄長度,最終最長的即為答案
複雜度為O(n)的思路是,定義首指標first和尾指標end記錄不重複子串,每次迭代判斷尾指標end所指向的字元是否已經出現在子串(first,end-1)中,若不存在則尾指標向後移動,若存在則將首指標first移動到與目前尾指標end所指向字元相等的字元的下標,並且移動過程中應把存在標記flag重新設定為false,最後首指標和尾指標再一起向後移動一位得到一個新的不重複子串(first,end-1)。
舉例說明: 字串abcdefgchijk,尾指標迭代到第二個c時,有不重複子串abcdefg,目前首指標指向a,尾指標指向第二個c,為了保證首尾指標所截得的子串不出現重複字元,首指標應該開始移動,每次移動的時候把對應的字元存在標誌改成false,即a、b的存在標誌改成false,這時首指標到達第一個c,最後再將首指標和尾指標共同後移一位得到新的子串(first,end-1)即defgc,然後尾指標一直迭代到尾處,至此完成,最終得到最長不重複子串defgchijk
具體程式碼如下:
import java.util.ArrayList; import java.util.Arrays; public class Solution { /*public static void main(String[] args) { Solution s = new Solution(); System.out.println(s.lengthOfLongestSubstring("abcdefgchijklmn")); }*/ public int lengthOfLongestSubstring(String s) { if(s.equals("")||s==null) return 0; char[] arr = s.toCharArray(); boolean[] flag = new boolean[256];//標記下標對應的字元是否出現,下標對應char的值 int length = arr.length; int first = 0; int end = 0; int max_length = 0; while(end<length){ if(!flag[(int)arr[end]]){ flag[(int)arr[end++]] = true; } else{ while(arr[first]!=arr[end]){ flag[(int)arr[first++]] = false; } first++; end++; } max_length = Math.max(max_length, end-first); } return max_length; } }