patternjavaMinor
Longest substring with no repetitions
Viewed 0 times
withsubstringlongestrepetitions
Problem
This is the code I came up with.It seems correct.
I am interested in:
1) Improvements on code
2) How can it be better than this? i.e. this is
Thanks
I am interested in:
1) Improvements on code
2) How can it be better than this? i.e. this is
O(N^2) Could I have done better in complexity? What should I have read to do it? Thanks
public int lengthOfLongestSubstringNoRepetitions(String s) {
if(s == null || s.trim().equals(""))
return 0;
Map seen = new HashMap();
int max = Integer.MIN_VALUE;
for(int i = 0; i < s.length(); i++){
for(int j = i; j < s.length(); j++){
char c = s.charAt(j);
if(seen.containsKey(new Character(c))){
//duplicate in substring
int tmp = j - i;
if(max < tmp) max = tmp;
break;
}
else{
seen.put(new Character(c),true);
if(j == s.length() -1){
//Reached the end of string.Add one to get the range
if(max < (j - i + 1)) max = (j - i + 1);
}
}
}
seen.clear();
}
return (max == Integer.MIN_VALUE)?s.length():max;
}Solution
Here's an O(n) solution. It replaces the Map with a char-indexed vector of the index where each char was last seen.
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 max)
max = len;
seen[ch] = j;
}
return max;
}Code Snippets
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;
}Context
StackExchange Code Review Q#9120, answer score: 5
Revisions (0)
No revisions yet.