Given a string, find the longest substring without repeating characters.
For example, for string “abccdefgh”, the longest substring is “cdefgh”.
import java.util.HashSet;
public class Substring {
public static void main(String[] args) {
// System.out.println(longest("abccdefgh"));
// System.out.println(longest(""));
// System.out.println(longest("cd"));
// System.out.println(longest("cc"));
System.out.println(longest("abcdefghabcdefgh"));
}
public static String longest(String str) {
if(str != null && str.length() > 0) {
HashSet<Character> hs = new HashSet<>();
HashSet<Character> hsTemp = new HashSet<>();
for(char ch : str.toCharArray()) {
if(!hsTemp.add(ch) && hsTemp.size() > hs.size()) {
hs.clear();
hs.addAll(hsTemp);
hsTemp.clear();
hsTemp.add(ch);
}
}
if(hs.isEmpty() || hsTemp.size() > hs.size()) {
StringBuilder sb = new StringBuilder();
for(char ch : hsTemp)
sb.append(ch);
return sb.toString();
}
else {
StringBuilder sb = new StringBuilder();
for(char ch : hsTemp)
sb.append(ch);
return sb.toString();
}
} else {
return null;
}
}
}
For example, for string “abccdefgh”, the longest substring is “cdefgh”.
import java.util.HashSet;
public class Substring {
public static void main(String[] args) {
// System.out.println(longest("abccdefgh"));
// System.out.println(longest(""));
// System.out.println(longest("cd"));
// System.out.println(longest("cc"));
System.out.println(longest("abcdefghabcdefgh"));
}
public static String longest(String str) {
if(str != null && str.length() > 0) {
HashSet<Character> hs = new HashSet<>();
HashSet<Character> hsTemp = new HashSet<>();
for(char ch : str.toCharArray()) {
if(!hsTemp.add(ch) && hsTemp.size() > hs.size()) {
hs.clear();
hs.addAll(hsTemp);
hsTemp.clear();
hsTemp.add(ch);
}
}
if(hs.isEmpty() || hsTemp.size() > hs.size()) {
StringBuilder sb = new StringBuilder();
for(char ch : hsTemp)
sb.append(ch);
return sb.toString();
}
else {
StringBuilder sb = new StringBuilder();
for(char ch : hsTemp)
sb.append(ch);
return sb.toString();
}
} else {
return null;
}
}
}