-
3. Longest Substring Without Repeating Characters javaLeetCode_Study_Plan/Algorithm 2022. 12. 21. 11:24
https://leetcode.com/problems/longest-substring-without-repeating-characters/
Queue를 이용한 풀이
class Solution { public static int lengthOfLongestSubstring(String s) { Queue<Character> q = new LinkedList<>(); int maxLen = 0; for(int i=0 ; i<s.length() ; i++){ while(q.contains(s.charAt(i))) { maxLen = Math.max(maxLen, q.size()); q.poll(); } q.add(s.charAt(i)); maxLen = Math.max(maxLen, q.size()); } return maxLen; } }
HashMap을 이용한 풀이
class Solution { public int lengthOfLongestSubstring(String s) { int maxLen = 0; int i,j=0; Map<Character,Integer> charMap = new HashMap<Character,Integer>(); for(i =0;i<s.length();i++) { while(charMap.containsKey(s.charAt(i))) { maxLen=Math.max(maxLen,charMap.size()); charMap.remove(s.charAt(j++)); } charMap.put(s.charAt(i),i); } maxLen=Math.max(maxLen,charMap.size()); return maxLen; } }
'LeetCode_Study_Plan > Algorithm' 카테고리의 다른 글
695. Max Area of Island java (0) 2022.12.22 733. Flood Fill java (0) 2022.12.22 567. Permutation in String java (0) 2022.12.21 🎵 19. Remove Nth Node From End of List java (0) 2022.12.21 876. Middle of the Linked List java (0) 2022.12.21