-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
61 lines (55 loc) · 1.48 KB
/
main.go
File metadata and controls
61 lines (55 loc) · 1.48 KB
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
61
// Source: https://leetcode.com/problems/clear-digits
// Title: Clear Digits
// Difficulty: Easy
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// You are given a string `s`.
//
// Your task is to remove **all** digits by doing this operation repeatedly:
//
// - Delete the first digit and the **closest non-digit** character to its left.
//
// Return the resulting string after removing all digits.
//
// **Example 1:**
//
// ```
// Input: s = "abc"
// Output: "abc"
// Explanation:
// There is no digit in the string.
// ```
//
// **Example 2:**
//
// ```
// Input: s = "cb34"
// Output: ""
// Explanation:
// First, we apply the operation on `s[2]`, and `s` becomes `"c4"`.
// Then we apply the operation on `s[1]`, and `s` becomes `""`.
//
// **Constraints:**
//
// - `1 <= s.length <= 100`
// - `s` consists only of lowercase English letters and digits.
// - The input is generated such that it is possible to delete all digits.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package main
// Use stack
func clearDigits(s string) string {
n := len(s)
stack := make([]byte, 0, n)
for i := range n {
ch := s[i]
if '0' <= ch && ch <= '9' { // is digit
if len(stack) > 0 {
stack = stack[:len(stack)-1] // pop
}
} else {
stack = append(stack, ch) // push
}
}
return string(stack)
}