大纲
- 题目
- 地址
- 内容
- 解题
- 代码地址
题目
地址
https://leetcode.com/problems/clear-digits/description/
内容
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.
解题
这题就是要从一个字符串中去除数字以及紧挨着它左侧的第一个非数字字符。要将这个逻辑一直执行到所有数字去除掉。
我们可以遍历这个字符串,将其非数字字符保存到新的字符串中;一旦遇到数字,则再从新的字符串中去除最后一个字符。
#include <string>
using namespace std;class Solution {
public:string clearDigits(string s) {string result = "";for (int i = 0; i < s.size(); i++) {if (s[i] >= '0' && s[i] <= '9' && result.size() > 0) {result = result.substr(0, result.size() - 1);} else if (s[i] >= 'a' && s[i] <= 'z') {result += s[i];}}return result;}
};
代码地址
https://github.com/f304646673/leetcode/tree/main/3174-Clear-Digits/cplusplus