forked from banjodayo39/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Array] Add a solution to Longest Substring with At Most Two Distinct…
… Characters
- Loading branch information
Showing
2 changed files
with
44 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/ | ||
* Primary idea: Slding window, use dictionary to check substring is valid or not, and | ||
note to handle the end of string edge case | ||
* | ||
* Time Complexity: O(n), Space Complexity: O(n) | ||
* | ||
*/ | ||
|
||
class LongestSubstringMostTwoDistinctCharacters { | ||
func lengthOfLongestSubstringTwoDistinct(_ s: String) -> Int { | ||
var start = 0, longest = 0, charFreq = [Character: Int]() | ||
let sChars = Array(s) | ||
|
||
for (i, char) in sChars.enumerated() { | ||
if let freq = charFreq[char] { | ||
charFreq[char] = freq + 1 | ||
} else { | ||
if charFreq.count == 2 { | ||
longest = max(longest, i - start) | ||
|
||
while charFreq.count == 2 { | ||
let charStart = sChars[start] | ||
charFreq[charStart]! -= 1 | ||
|
||
if charFreq[charStart] == 0 { | ||
charFreq[charStart] = nil | ||
} | ||
|
||
start += 1 | ||
} | ||
} | ||
|
||
charFreq[char] = 1 | ||
} | ||
} | ||
|
||
return max(longest, sChars.count - start) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters