Longest Substring Without Repeating Characters

Question:

Find the longest sub-string without repeating characters. For example, if the given string is "abcdcefg", the longest sub-string without repeating characters is "dcefg".


Analysis:

In order to check whether the character repeats or not, the common approach is to build a hash table. When the character appears for the first time, we set its value in the hash table to be true, therefore, when that character appears again, we know the current sub-string will have duplicated character if we continue.


When we continue with a new sub-sting, we should set the hash table value of the previous characters to be false (but not all of them, see the code below), and compare the current sub-string with the temp longest sub-string.


Code:

public class Test {
	public static void main(String[] args) {	
		Test t = new Test();
		System.out.println(t.lengthOfLongestSubstring("abcdcef"));	
	}
	
	int lengthOfLongestSubstring(String s) {
		  int n = s.length();
		  int i = 0, j = 0;
		  int maxLen = 0;
		  boolean exist[] = new boolean[256];
		  for (int k = 0; k < 255; k++) {
			  exist[k] = false;
		  }
		  while (j < n) {
		    if (exist[s.charAt(j)]) {
		      maxLen = max(maxLen, j - i);
		      while (s.charAt(i) != s.charAt(j)) {
		        exist[s.charAt(i)] = false;
		        i++;
		      }
		      i++;
		      j++;
		    } else {
		      exist[s.charAt(j)] = true;
		      j++;
		    }
		  }
		  maxLen = max(maxLen, n - i - 1);
		  return maxLen;
	}
	
	int max(int a, int b) {
		return a > b ? a : b;
	}
}

From: http://blog.csdn.net/beiyetengqing



你可能感兴趣的:(算法,(Algorithm))