Longest Substring Without Repeating Characters (返回最长无字符重复的子串长度)

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.

public class Solution {
	// 没有重复的最长子串的长度
	public int lengthOfLongestSubstring(String s) {
		int[] hash=new int[256];
		int len = s.length();
		int i=0;
		int j=0;
		int maxLen = 0;
		int tempLen = 0;
		int tIndex = 0;
		char[] arr = s.toCharArray();
		for(i=0;i<256;i++){
			hash[i]=-1;
		}
		for (i = 0; i < len; i++) {
			// 复杂度为n
			int ic=(int)arr[i];
			if (hash[ic]==-1) {
				hash[ic]=i;
				tempLen++;
			} else {
				// 获取重复出现字符串的最小索引tIndex
				tIndex = hash[ic];
				// 当出现重复时,需要清空已有的标记
				 for (j = 0; j < 256; j++) {
				     hash[j]=-1;
				 }
				// 因为i跳过本次循环后会自动+1
				i = tIndex;
				tempLen = 0;
			}
			maxLen = maxLen > tempLen ? maxLen : tempLen;
		}
		return maxLen;
	}

	public static void main(String args[]) {
		Solution s = new Solution();
//		int l = s.lengthOfLongestSubstring("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco");
//		int l = s.lengthOfLongestSubstring("hchzvfrkmlnozjk");
		int l = s.lengthOfLongestSubstring("qopubjguxhxdipfzwswybgfylqvjzhar");
		System.out.print(l);
	}
}


你可能感兴趣的:(LetCode)