Note: The forum is auto-replacing \1 in the pattern string with `, so you should make the opposite adjustment to compile.
163 characters:
public static String l(String s){String r="",t;int l=s.length(),i=0,j;for(;i++<l;)for(j=l;j>=i;)if(!(t=s.substring(j-i,j--)).matches(".*(.).*\\1.*"))r=t;return r;}
Longified:
public static String longest(String s) {
String longest = "";
for (int i = 1; i <= s.length(); i++) {
for (int j = s.length(); j >= i; j--) {
String substring = s.substring(j - i, j);
if (!substring.matches(".*(.).*\\1.*"))
longest = substring;
}
}
return longest;
}
The method enumerates all substrings of s (except the ones with length 0) and returns the longest one which does not have a repeated character determined using matches
. The outer loop chooses the length of the substring starting with the shortest. The inner loop picks a substring among those with the specified length (in particular, it chooses the second argument to be passed to substring
). For example, longest("abcde")
would start with substrings of length 1, of which there are 5 (“a”, “b”, “c”, “d”, “e”), and then with substrings of length 2, of which there are 4 (“ab”, “bc”, “cd”, “de”), and then with substrings of length 3, of which there are 3 (“abc”, “bcd”, “cde”), etc.
Below is another one that does the search backwards, starting with the longest substrings and working its way toward the shortest. The first substring encountered that does not have a repeated character is returned. The previous version is shorter because the first return statement is replaced by a shorter assignment statement.
165 characters:
public static String l(String s){String t;int l=s.length(),i=l,j;for(;i>0;i--)for(j=l;j>=i;)if(!(t=s.substring(j-i,j--)).matches(".*(.).*\\1.*"))return t;return "";}
Longified:
public static String longest(String s) {
for (int i = s.length(); i > 0; i--) {
for (int j = s.length(); j >= i; j--) {
String t = s.substring(j - i, j);
if (!t.matches(".*(.).*\\1.*"))
return t;
}
}
return "";
}
I’m not too familiar with regexes, but I bet there’s a shorter and fancier way to do this with java.util.regex
, possibly without loops.