-
leetCode - Longest Substring Without Repeating Characters(LinkedList)프로그래밍/algorithm 2021. 7. 14. 12:29
문제
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Example 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.
풀이
내가 이 문제를 풀면서 어려웠던 점.
- 반복되는 문자열이 나왔을 때, 이 전에 반복하지 않은 문자열을 어디에 저장하면 될지 모르겠더라...
해결 방법:
- start와 maxLength라는 변수를 따로 둔다.
- 반복되는 문자열을 찾는 다면 start를 이동 시켜 준다.
- start를 통해서 maxLength를 구해준다,
const lengthOfLongestSubstring = function(s) { let start = 0, maxLength = 0; let map = new Map(); for(let i =0; i<s.length; i++) { if(map.get(s[i]) >= start) start = map.get(s[i]) + 1; map.set(s[i], i); maxLength = Math.max(maxLength, i-start+1); } return maxLength; };
'프로그래밍 > algorithm' 카테고리의 다른 글
leetCode - Longest Palindromic Substring(DP) (0) 2021.07.16 leetCode-Median of Two Sorted Arrays(binary search) (0) 2021.07.15 leeCode -Add Two Numbers(LinkedList) (0) 2021.07.14 leetCode - Reverse Linked List(LinkedList) (0) 2021.07.07 leetCode (Remove Linked List Elements)-LinkedList (0) 2021.07.06