1. 程式人生 > >LeetCode3 Longest Substring Without Repeating Characters

LeetCode3 Longest Substring Without Repeating Characters

true 字串 當前 字符 return 記錄 pos trac for

題目:

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

譯:給定一個字符串,找到沒有反復字符的最長子字符串。

例:字符串“abcabcbb"的最大字串位”abc",長度為3。


方法一:以每個字符作為起始字符。計算不反復字符串的長度。並記錄最大的串的長度。hash表(一個boolean類型的數組,大小為256,數組的索引可相應字符的ASCII碼)記錄該字符是否出現過。

public static int lengthOfLongestSubstringA(String s) {
<span style="white-space:pre">	</span>//book存儲字符出現的位置。索引表示字符ASCII碼,值表示最後一次在字符串中出現的位置
    boolean[] book = new boolean[256];
<span style="white-space:pre">	</span>int maxSubLen = 0;  
<span style="white-space:pre">	</span>int[] lenOff = new int[s.length()];//記錄位置 
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>for(int start=0;start<s.length();start++){   
<span style="white-space:pre">		</span>//初始化標誌位
<span style="white-space:pre">		</span>for(int i=0;i<256;i++){
<span style="white-space:pre">			</span>book[i] = false;
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>for (int p  = start; p  < s.length();p ++) {
<span style="white-space:pre">			</span>int off = s.charAt(p);
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>if (book[off]) {//字符出現過 
<span style="white-space:pre">				</span>break;
<span style="white-space:pre">			</span>} 
<span style="white-space:pre">			</span>lenOff[start] = p-start+1; 
<span style="white-space:pre">			</span>book[off] = true;
<span style="white-space:pre">			</span>if (maxSubLen < lenOff[start]){
<span style="white-space:pre">				</span>maxSubLen = lenOff[start];
<span style="white-space:pre">			</span>} 
<span style="white-space:pre">		</span>} 
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>return maxSubLen;
}

方法二: 統計可能出現的最大子字符串。須要在hash表(一個整數數組,數組大小為256,每一個索引相應一個字符的ASCII碼)中記錄上次出現該字符的位置。僅僅進行一次遍歷。假設出現反復字符,依據上次出現該字符的位置。重置可能為最大字符串的起始位置,比方上次出現的位置是n,那下次統計的字符串的起始位置就是n+1。

public static int lengthOfLongestSubstring(String s) {
	//book存儲字符出現的位置,索引表示字符ASCII碼。值表示最後一次在字符串中出現的位置
    int[] book = new int[128];
	int maxSubLen = 0; 
	int subStrStart = 0;
	int[] lenOff = new int[s.length()];
	
	for(int i =0;i<128;i++)
	    book[i]  = -1;
	    
	for (int p  = 0; p  < s.length();p ++) {
		int off = s.charAt(p); 
		
		if (book[off]>=subStrStart) {//字符在當前字串中出現過   
			subStrStart = book[off]+1; //又一次計算字串
		} 

	    lenOff[subStrStart] = p-subStrStart+1;
	    
		if (maxSubLen < lenOff[subStrStart]){
			maxSubLen = lenOff[subStrStart];
		} 
		book[off] = p;//字符最後一次出現的位置
	} 
	return maxSubLen;
}


LeetCode3 Longest Substring Without Repeating Characters