刷题Day1

题目描述

刷题Day1_第1张图片
image.png

代码

思路:使用了栈后进先出的思想

class Solution {
    public String removeOuterParentheses(String S) {
        StringBuilder sb = new StringBuilder();

        Stack stack = new Stack<>();
        int start = 0;
        int end = 0;
        boolean flag = false;
        for(int i = 0;i

延伸

给一个字符串a#bc#d#e#f,要求输出两个#号中间的字符串,但是如果前一个字符串使用了该#,后面的就不能使用。所以该字符串输出结果应该是bc e

代码

这里同样使用了栈的思路。该题目类似于微博的话题。

public static List getString(String S) {
        List list = new ArrayList<>();
        Stack stack = new Stack<>();
        int start = 0;
        int end = 0;

        for (int index = 0; index < S.length(); index++) {
            if (S.charAt(index) == '#') {
                if (stack.isEmpty()) {
                    stack.push(S.charAt(index));
                    start = index;
                } else {
                    stack.pop();
                    end = index;
                    list.add(S.substring(start + 1, end));
                }
            }
        }
        return list;
    }

你可能感兴趣的:(刷题Day1)