File tree 2 files changed +61
-0
lines changed
2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change 170
170
| 295 | Find Median from Data Stream | [ Ruby] ( ./algorithms/ruby/0295-find-median-from-data-stream.rb ) | Hard |
171
171
| 299 | Bulls and Cows | [ Ruby] ( ./algorithms/ruby/0299-bulls-and-cows.rb ) [ Python3] ( ./algorithms/python3/0299-bulls-and-cows.py ) | Medium |
172
172
| 300 | Longest Increasing Subsequence | [ Ruby] ( ./algorithms/ruby/0300-longest-increasing-subsequence.rb ) | Medium |
173
+ | 316 | Remove Duplicate Letters | [ Ruby] ( ./algorithms/ruby/0316-remove-duplicate-letters.rb ) | Medium |
173
174
| 319 | Bulb Switcher | [ Ruby] ( ./algorithms/ruby/0319-bulb-switcher.rb ) | Medium |
174
175
| 322 | Coin Change | [ Ruby] ( ./algorithms/ruby/0322-coin-change.rb ) | Medium |
175
176
| 328 | Odd Even Linked List | [ Ruby] ( ./algorithms/ruby/0328-odd-even-linked-list.rb ) | Medium |
Original file line number Diff line number Diff line change
1
+ # frozen_string_literal: true
2
+
3
+ # 316. Remove Duplicate Letters
4
+ # Medium
5
+ # https://leetcode.com/problems/remove-duplicate-letters
6
+
7
+ =begin
8
+ Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is
9
+ the smallest in lexicographical order among all possible results.
10
+
11
+ Example 1:
12
+ Input: s = "bcabc"
13
+ Output: "abc"
14
+
15
+ Example 2:
16
+ Input: s = "cbacdcbc"
17
+ Output: "acdb"
18
+
19
+ Constraints:
20
+ 1 <= s.length <= 104
21
+ s consists of lowercase English letters.
22
+ =end
23
+
24
+ # @param {String} s
25
+ # @return {String}
26
+ def remove_duplicate_letters ( s )
27
+ count_hash = Hash . new { |h , k | h [ k ] = 0 }
28
+ stack = [ ]
29
+ selected_set = Set . new
30
+
31
+ s . each_char do |char |
32
+ count_hash [ char ] += 1
33
+ end
34
+
35
+ s . each_char do |char |
36
+ count_hash [ char ] -= 1
37
+ unless selected_set . include? ( char )
38
+ while !stack . empty? && count_hash [ stack . last ] > 0 && stack . last > char
39
+ selected_set . delete ( stack . pop )
40
+ end
41
+
42
+ stack << char
43
+ selected_set << char
44
+ end
45
+ end
46
+
47
+ stack . join
48
+ end
49
+
50
+ # **************** #
51
+ # TEST #
52
+ # **************** #
53
+
54
+ require "test/unit"
55
+ class Test_length_of_longest_substring < Test ::Unit ::TestCase
56
+ def test_
57
+ assert_equal "abc" , remove_duplicate_letters ( "bcabc" )
58
+ assert_equal "acdb" , remove_duplicate_letters ( "cbacdcbc" )
59
+ end
60
+ end
You can’t perform that action at this time.
0 commit comments