1. 程式人生 > >【LeetCode】159. Longest Substring with At Most Two Distinct Characters

【LeetCode】159. Longest Substring with At Most Two Distinct Characters

Difficulty: Hard

 More:【目錄】LeetCode Java實現

Description

Given a string S, find the length of the longest substring T that contains at most two distinct characters.
For example,
Given S = “eceba”,
T is "ece" which its length is 3.

Intuition

方法一:假設有一個滑動視窗,視窗左右兩邊的下標分別記為left和right。遍歷字串,依次確定left和right。具體實現見程式碼(稍微難理解一點)

方法二:還是引入一個滑動視窗,視窗左右兩邊的下標分別記為left和right。再引入一個numDistinct變數,用於記錄視窗中已經出現的不同字元次數。此外,使用一個int[258]來模擬雜湊表,記錄每個字元出現的次數count。

  遍歷字串(right右移),當遇到的字元出現次數為0時,numDistinct++; 當numDistinct的次數超過2時,說明left需要往右移,在left往右移的過程中,減少所指字元的count,最終使得numDistinct=2,才暫停left的右移。

  方法二容易理解,且可以用於求解k個不同字元組成的最長子字元。下面程式碼中方法二就是實現k個不同字元的情況。

Solution

	//Method1: Longest Substring with At Most Two Distinct Characters 
	public static int lengthOfLongestSubstringTwoDistinct1(String s) {
		if(s==null || s.length()<=0)
			return 0;
		int left=0;
		int right=-1;
		int maxLen=0;
		for(int i=1;i<s.length();i++) {
			if(s.charAt(i)==s.charAt(i-1))	continue;
			if(right!=-1 && s.charAt(i)!=s.charAt(right)) {
				maxLen=Math.max(maxLen, i-left);
				left=right+1;
			}
			right=i-1;
		}
		return Math.max(s.length()-left,maxLen);
	}
	
	//Method2: Longest Substring with At Most k Distinct Characters 
	public static int lengthOfLongestSubstringTwoDistinct2(String s,int k) {
		if(s==null || s.length()<=0)
			return 0;
		int[] count=new int[256];
		int numDistinct=0;
		int maxLen=0;
		int left=0;
		for(int right=0;right<s.length();right++) {
			if(count[s.charAt(right)]==0) numDistinct++;
			count[s.charAt(right)]++;
			while(numDistinct>k) {
				count[s.charAt(left)]--;
				if(count[s.charAt(left)]==0) numDistinct--;
				left++;
			}
			maxLen=Math.max(maxLen, right-left+1);
		}
		return maxLen;
	}

  

Complexity

Time complexity : O(n)

Space complexity :  O(1)

What I've learned

1. 方法一中,i可能會越界,所以程式碼第16行別忘記了s.length()-left。

2. 方法一里的left,right以及 i指標之間的關係要搞清楚。

3.方法二中引入了numDistinct,非常方便,有時候往往多設定一個變數,就能實現所需要的功能

 

 More:【目錄】LeetCode Java實現