
Longest Substring Without Repeating Characters - LeetCode
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) return 0;
Set<Character> characterSet = new HashSet<>();
int left = 0;
int right = 0;
int answer = 0;
characterSet.add(s.charAt(left));
while (right < s.length()){
if (left == right || !characterSet.contains(s.charAt(right))){
characterSet.add(s.charAt(right));
answer = Math.max(characterSet.size(), answer);
right += 1;
} else{
while (s.charAt(left) != s.charAt(right)) {
characterSet.remove(s.charAt(left));
left += 1;
}
if (left < right) {
characterSet.remove(s.charAt(left));
left += 1;
}
}
}
return answer;
}
}
left == right || !characterSet.contains(s.charAt(right))while (s.charAt(left) != s.charAt(right))속도는 전반적으로 무난했으나 풀이가 명확하지 않다.

class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) return 0;
Map<Character, Integer> characterMap = new HashMap<>();
int left = 0;
int right = 0;
int answer = 0;
characterMap.put(s.charAt(left), 1);
while (right < s.length()){
System.out.println("left: " + left + " right: " + right);
if (left == right || !characterMap.containsKey(s.charAt(right))){
characterMap.put(s.charAt(right), 1);
answer = Math.max(right - left + 1, answer);
right += 1;
} else{
while (s.charAt(left) != s.charAt(right)) {
characterMap.remove(s.charAt(left));
left += 1;
}
if (left < right) {
characterMap.remove(s.charAt(left));
left += 1;
}
}
}
return answer;
}
}
Set이 아닌 Map을 사용하여 key를 통한 접근을 시도하였으나 큰 차이는 없다.

class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> used = new HashMap<>();
int answer = 0;
int left = 0;
int right = 0;
for (char c: s.toCharArray()){
if (used.containsKey(c) && left <= used.get(c)){
left = used.get(c) + 1;
} else {
answer = Math.max(answer, right - left + 1);
}
used.put(c, right);
right += 1;
}
return answer;
}
}
