Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

从字符串中移除星号 #156

Open
yankewei opened this issue Aug 28, 2022 · 1 comment
Open

从字符串中移除星号 #156

yankewei opened this issue Aug 28, 2022 · 1 comment
Labels
中等 题目难度为中等 字符串 题目类型为字符串 题目包含栈解法

Comments

@yankewei
Copy link
Owner

给你一个包含若干星号*的字符串s

在一步操作中,你可以:

  • 选中s中的一个星号。
  • 移除星号 左侧 最近的那个 非星号 字符,并移除该星号自身。
  • 返回移除 所有 星号之后的字符串。

注意:

  • 生成的输入保证总是可以执行题面中描述的操作。
  • 可以证明结果字符串是唯一的。

示例 1:

输入:s = "leet**cod*e"
输出:"lecoe"
解释:从左到右执行移除操作:
- 距离第 1 个星号最近的字符是 "leet**cod*e" 中的 't' ,s 变为 "lee*cod*e" 。
- 距离第 2 个星号最近的字符是 "lee*cod*e" 中的 'e' ,s 变为 "lecod*e" 。
- 距离第 3 个星号最近的字符是 "lecod*e" 中的 'd' ,s 变为 "lecoe" 。
不存在其他星号,返回 "lecoe" 。

示例 2:

输入:s = "erase*****"
输出:""
解释:整个字符串都会被移除,所以返回空字符串。

提示:

  • 1 <= s.length <= 105
  • s 由小写英文字母和星号 * 组成
  • s 可以执行上述操作

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/removing-stars-from-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 中等 题目难度为中等 题目包含栈解法 字符串 题目类型为字符串 labels Aug 28, 2022
@yankewei
Copy link
Owner Author

暴力模拟

可以直接根据题意模拟即可

class Solution {

    /**
     * @param String $s
     * @return String
     */
    function removeStars($s) {
        while (true) {
            $str_pos = strpos($s, "*");
            if ($str_pos === 0) {
                $s = substr($s, 1);
            }
            if ($str_pos === false) {
                break;
            }
            $s = substr($s, 0, $str_pos-1) . substr($s, $str_pos+1);
        }
        
        return $s;
    }
}

看到了移除左侧字符,可以联想到用栈的概念

class Solution {

    /**
     * @param String $s
     * @return String
     */
    function removeStars($s) {
        $stack = [];

        for ($i = 0; $i < strlen($s); $i++) {
            $s[$i] !== "*" ? array_push($stack, $s[$i]) : array_pop($stack);
        }

        return implode('', $stack);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 题目难度为中等 字符串 题目类型为字符串 题目包含栈解法
Projects
None yet
Development

No branches or pull requests

1 participant