自学内容网 自学内容网

【百日算法计划】:每日一题,见证成长(018)

题目

删除连续重复字符

字符串删除掉连续的3个重复的字符,比如"abbbc" 返回"ac" ,“abbbaad” 返回"d"

思路

  • 构造一个对象,属性为元素及个数;
  • 将对象加入到栈中,同时判断其元素的个数;
  • 当元素个数等于 3 时,则弹出栈。
public class Code02 {
    Stack<CharWithCount> stack = new Stack<>();
    /**
     * 用栈记录不能消除的元素
     * @param str
     * @return
     */
    public String remove(String str){
        int n = str.length();
        for (int i = 0; i < n; i++) { //顺序处理每个字符
            char c = str.charAt(i);
            //栈为空
            if (stack.isEmpty()){
                stack.push(new CharWithCount(c, 1));
                continue;
            }
            //栈不为空 栈顶元素跟c比较 且不相同
            CharWithCount topChar = stack.peek();
            if (topChar.c != c){
                stack.push(new CharWithCount(c, 1));
                continue;
            }

            //栈顶元素跟c相同,比较个数,如果已有2个,则弹出
            if (topChar.count == 2){
                stack.pop();
                continue;
            }
            //栈顶元素跟c相同 但不满足连连消
            topChar.count++;
        }

        //最后开始输出栈里面的元素
        int size = stack.size();
        char[] arr = new char[size];
        while (!stack.isEmpty()){
            char c = stack.pop().c;
            arr[size-1] = c;
            size--;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            sb.append(String.valueOf(arr[i]));
        }
        return sb.toString();
    }

    public class CharWithCount{
        public char c;
        public int count;
        public CharWithCount(){}
        public CharWithCount(char c,int count){
            this.c = c;
            this.count = count;
        }
    }
}

原文地址:https://blog.csdn.net/yqq962464/article/details/142393029

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!