-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0316-remove-duplicate-letters.rb
60 lines (48 loc) · 1.27 KB
/
0316-remove-duplicate-letters.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# frozen_string_literal: true
# 316. Remove Duplicate Letters
# Medium
# https://leetcode.com/problems/remove-duplicate-letters
=begin
Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is
the smallest in lexicographical order among all possible results.
Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
Constraints:
1 <= s.length <= 104
s consists of lowercase English letters.
=end
# @param {String} s
# @return {String}
def remove_duplicate_letters(s)
count_hash = Hash.new { |h, k| h[k] = 0 }
stack = []
selected_set = Set.new
s.each_char do |char|
count_hash[char] += 1
end
s.each_char do |char|
count_hash[char] -= 1
unless selected_set.include?(char)
while !stack.empty? && count_hash[stack.last] > 0 && stack.last > char
selected_set.delete(stack.pop)
end
stack << char
selected_set << char
end
end
stack.join
end
# **************** #
# TEST #
# **************** #
require "test/unit"
class Test_length_of_longest_substring < Test::Unit::TestCase
def test_
assert_equal "abc", remove_duplicate_letters("bcabc")
assert_equal "acdb", remove_duplicate_letters("cbacdcbc")
end
end