首页 > 其他 > 详细

remove 3 duplicates

时间:2018-10-02 10:27:52      阅读:142      评论:0      收藏:0      [点我收藏+]

 

 

private static void remove(String s) {
        if (s == null || s.length() == 0) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        Stack<Character> st1 = new Stack<>();
        Stack<Integer> st2 = new Stack<>();
        for (char c : s.toCharArray()) {
           if (!st2.isEmpty() && c != st1.peek() && st2.peek() >= 3) {
                st1.pop();
                st2.pop();

            }
            if (st2.isEmpty()) {
                st1.push(c);
                st2.push(1);
            } else if (c == st1.peek()) {
                int cnt = st2.pop();
                cnt++;
                st2.push(cnt);
            } else {
                st1.push(c);
                st2.push(1);
            }
        }
        if (!st2.isEmpty() && st2.peek() >= 3) {
            st1.pop();
            st2.pop();
        }

        while (!st2.isEmpty()) {
            int cnt = st2.pop();
            char c = st1.pop();
            for (int i = 0; i < cnt; i++) {
                sb.append(c);
            }
        }
        System.out.println(sb.reverse().toString());
    }

  

remove 3 duplicates

原文:https://www.cnblogs.com/apanda009/p/9736231.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!