Below is the example for finding out the longest subString with no repetition in java subString.........
public class LongestSubStringWithNoRepetition {
public static void main(String args[]) {
int x = lengthOfLongestSubstringNoRepetitions("Hi, this is a tesgft string.jgdfgdfkhfjrestjkbngfld ");
System.out.println(""+x);
}
public static int lengthOfLongestSubstringNoRepetitions(String s) {
if (s == null)
return 0;
// Trimming input even for the non-empty case is more consistent.
final String str = s.trim();
if (str.equals(""))
return 0;
int seen[] = new int[Character.MAX_VALUE+1];
for (int i = 0; i <= Character.MAX_VALUE; ++i)
seen[i] = -1;
int max = 1;
int len = 0;
for (int j = 0; j < str.length(); ++j) {
char ch = str.charAt(j);
// If ch was recently seen,
// counting must restart after the last place it was seen.
// Otherwise, it adds 1 to the length.
len = Math.min(j-seen[ch], len+1);
if (len > max)
max = len;
seen[ch] = j;
}
return max;
}
}
Below is the output........
12
No comments:
Post a Comment