하단 Title 클릭 시 해당 문제 페이지로 이동합니다.
String s에서 중복되는 글자가 없는 가장 긴 substring의 길이를 구하여라
0 <= s.length <= 5 * 10^4s consists of English letters, digits, symbols and spaces예시 1
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
예시 2
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
예시 3
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Key: Character, Value: index를 저장한다.result를 Map size와 비교해서 큰 값으로 저장한다.vbvf인 경우 두번째 v에서 걸렸을 때, b부터 다시 시작해야하기 때문result를 비교하여 큰 값을 returnimport java.util.HashMap;
import java.util.Map;
class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int result = 0;
for (int i = 0, sLength = s.length(); i < sLength; i++) {
if (map.containsKey(s.charAt(i))) {
result = Math.max(result, map.size());
i = map.get(s.charAt(i)) + 1;
map.clear();
}
map.put(s.charAt(i), i);
}
return Math.max(result, map.size());
}
}