https://leetcode.com/problems/longest-substring-without-repeating-characters/
class Solution {
public int lengthOfLongestSubstring(String s) {
int start_idx = 0;
int end_idx = 0;
int result = 0;
while (end_idx <= s.length()) {
String ns = s.substring(start_idx, end_idx);
int[] asc = new int[128];
boolean flag = true;
for(char x : ns.toCharArray()) {
if (asc[(int)x] != 1) {
asc[(int)x] = 1;
}
else {
start_idx += 1;
flag = false;
break;
}
}
end_idx += 1;
if (flag && ns.length() > result) {
result = ns.length();
}
}
return result;
}
}
import java.util.HashSet;
public class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLength = 0;
int i=0, j=0;
int length = s.length();
HashSet<Character> stringSet = new HashSet<>();
while (j < length) {
if(i > j) break;
if (!stringSet.contains(s.charAt(j))){
stringSet.add(s.charAt(j++));
maxLength = Math.max(maxLength, j - i);
continue;
}
stringSet.remove(s.charAt(i++));
}
return maxLength;
}
}
내가 해결한 방법은 start_idx와 end_idx를 설정해 substring으로 잘라 for문을 돌면서 아스키코드로 전환시켜 중복을 체크하는 방법이다. 하지만 다른 사람의 코드를 보니 해시셋으로 중복 체크를 했고 최대값 체크, 루프문도 훨씬 간결하게 해결하여 가져와보았다.