牛客网真题-67-万万没想到之聪明的编辑字符串去重

万万没想到之聪明的编辑

http://www.nowcoder.com/questionTerminal/42852fd7045c442192fa89404ab42e92

一次遍历,考虑状态
用一个temp缓存字符子串,长度不超过3,比较当前字符与上一个字符是否相等
temp只有这几5种情况={空,a,aa,aab}
加上当前字符有这么几种状态{a,aa,aaa,ab,aab,aabb,aabc},但是可以合并,代码如下

package org.niuke.solution67;
import java.util.*;
public class Main {
    private static String solve(String s){
        Queue<Character> queue = new LinkedList<>();
        String res = "", temp = "";
        int pre = 0;
        for(int i = 0; i < s.length(); i++){
            queue.offer(s.charAt(i));
        }
        while (!queue.isEmpty()) {
            int last = temp.length() - 1;
            Character c = queue.poll();
            if(last < 0){
                temp += c;
                pre++;
            }else{
                if(c == temp.charAt(last)){
                    if(pre < 2){//bb 只有
                        pre++;
                        temp += c;
                    }else if(pre == 2){ //aab,aaa 都是直接丢弃
                        continue;
                    }
                }else{//ab aabc,aab
                    if(pre < 2){
                        res += temp;
                        temp = "" + c;
                        pre = 1;
                    }else{
                        if(temp.length() < 3){
                            temp += c;
                        }else{
                            res += temp;
                            temp = "" + c;
                            pre = 1;
                        }

                    }

                }
            }

        }
        return res + temp;
    }
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine());
        while (n > 0) {
            n--;
            String res = solve(scanner.nextLine());
            System.out.println(res);
        }
    }
}
全部评论
我俩的思路一样,感觉这样清晰些
点赞 回复 分享
发布于 2020-10-21 16:10

相关推荐

11-04 10:30
已编辑
门头沟学院 研发工程师
开心小狗🐶:“直接说答案”
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
11-21 11:29
已编辑
斯卡蒂味的鱼汤:知道你不会来数马,就不捞你😂最近数马疯狂扩招,招聘要求挺低的,你能力肯定够,应该就是因为太强了,知道你不会来才不捞你
投递腾讯云智研发等公司7个岗位
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务