Popular Posts

Saturday, February 18, 2012

Length of the longest substring without repeating characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substrings without repeating characters for “ABDEFGABEF” are “BDEFGA” and “DEFGAB”, with length 6.
public class LongestSubString {

public static void main(String[] args) {
String str
= "ABDEFGABEF";

// Used for tracking the position of last occurrence of character in the
// string.
int[] chars = new int[256];
for (int i = 0; i < 256; i++) {
chars
[i] = -1;
}

int maxLength = 1;
int currentLength = 1;

for (int i = 0; i < str.length(); i++) {
int lastOccrrenceIndex = chars[str.charAt(i)];
if (lastOccrrenceIndex == -1
|| (i - currentLength > lastOccrrenceIndex)) {
currentLength
++;
} else {
if (currentLength > maxLength)
maxLength
= currentLength;
currentLength
= i - lastOccrrenceIndex;
}
chars
[str.charAt(i)] = i;
}
if (currentLength > maxLength)
maxLength
= currentLength;
System
.out.println(maxLength);
}
}


Time Complexity: O(n + d) where n is length of the input string and d is number of characters in input string alphabet. For example, if string consists of lowercase English characters then value of d is 26.
Auxiliary Space: O(d)

Refer : http://www.geeksforgeeks.org/archives/15859

No comments:

Post a Comment