Game Development

LeetCode 3번 Longest Substring Without Repeating Characters 본문

Algorithms/Leet Code

LeetCode 3번 Longest Substring Without Repeating Characters

Dev Owen 2021. 7. 25. 19:30


문제 링크

 

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


문제

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:

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.

풀이

이 문제는 주어진 문자열에서 문자를 중복하여 사용하지 않고 가장 긴 문자열의 길이를 리턴하는 문제입니다.

class Solution {
public:
	int lengthOfLongestSubstring(string s)
	{
		map<char, int> dict;
		int maxLen = 0, begin = 0;
		char key;

		for (int i = 0; i < s.size(); i++)
		{
			key = s[i];

			// 현재 노드 안에 있고, 시작 지점이 현재 중복되는 노드보다 앞에 있을 경우
			if (dict.find(key) != dict.end() && dict[key] >= begin)
			{
				maxLen = max(maxLen, i - begin);
				begin = dict[key] + 1;
			}

			dict[key] = i;
		}
		return max(maxLen, (int)s.size() - begin);
	}
};
Time Submitted Status RunTime Memory
07/25/2021 19:21 Accepted 16 ms 8.5 MB

시간 복잡도 : O(N)

'Algorithms > Leet Code' 카테고리의 다른 글

LeetCode 4번 Median of Two Sorted Arrays  (0) 2023.09.23
LeetCode 6번 ZigZag Conversion  (0) 2021.08.04
LeetCode 5번 Longest Palindromic Substring  (0) 2021.07.25
LeetCode 2번 Add Two Numbers  (0) 2021.07.25
LeetCode 1번 Two Sum  (0) 2021.07.25
Comments