[LeetCode] Longest Substring Without Repeating Characters
개인적으로 공부하면서 기록하는 공간으로
잘못된 정보는 댓글을 통해 알려주시면 감사하겠습니다 :-)
▪ ▪ ▪ ▪ ▪
🎈문제
Given a string s, find the length of the longest substring without repeating characters.
Example1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example3:
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 substiring.
Constrints:
• 0 <= s.lenght <= 5 * 10^4
• s consists of English letters, digits, symbols and spaces.
💡 문제해석
주어진 문자열에서 알파벳이 중복되지 않고 가장 길게 연속되는 문자열의 일부를 반환하라는 문제이다.
🎈문제 풀이
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
let subStr = "";
let maxLength = 0;
for (let i = 0; i < s.length; i++) {
if (subStr.includes(s[i])) {
subStr = subStr.slice(subStr.indexOf(s[i]) + 1);
}
subStr += s[i];
if (maxLength < subStr.length) {
maxLength = subStr.length;
}
}
return maxLength;
};
① 연속되는 문자열을 담을 subStr 변수와 그 문자열의 길이를 담을 maxLength 변수를 선언한다.
② s의 문자열 길이만큼 for문을 돌린다.
③ subStr 변수에 s문자열의 i번째 문자가 포함되어있으면 해당 index + 1를 시작점으로 slice 하여 subStr에 재할당한다.
slice()
slice() 메소드는 배열의 begin부터 end 까지(end미포함) 새로운 배열 객체로 반환
형식) slice(시작index, [종료index])
④ subStr에 문자열의 i번째 문자를 더해준다.
⑤ 연속되는 문자열의 길이 maxLength가 새로 할당한 문자 subStr 문자열의 길이와 비교하여 더 큰 값을 maxLength에 할당한다.
⑥ 입력받은 문자열 s의 길이 만큼 for문을 돌고 난 뒤 maxLength를 리턴한다.
🎈문제 풀어보기
Longest Substring Without Repeating Characters - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Reference
✔ https://velog.io/@yejinh/알고리즘-LeetCode-Longest-Substring-Without-Repeating-Characters-3rk3n08jvu
댓글