如何在Java中删除字符串中的相邻重复项 [英] How to remove adjacent duplicates in a string in Java

查看:426
本文介绍了如何在Java中删除字符串中的相邻重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间以来,我一直在寻找这个答案. 我已经找到了许多使用HashSet或LinkedHashSet删除重复项的解决方案,但是它们都删除了所有重复项,我只在寻找相邻的重复项. " 说一个字符串是"ABBCDAABBBBBBBBBBOR" 要求的结果应该是"ABCDABOR",而不是"ABCDOR". 可以在O(n)中实现吗?谢谢.

I've been looking for this answer for a while. I've found numbers of solutions for removing duplicates using a HashSet or LinkedHashSet but they all remove all duplicates, I'm looking for only the adjacent ones. " Say a string is "ABBCDAABBBBBBBBOR" The required result should be "ABCDABOR" and not "ABCDOR". Could this be achived in O(n) ? Thanks.

推荐答案

确定:

StringBuilder sb = new StringBuilder();
char[] chars = text.toCharArray();
char previous = chars[0];
sb.append(chars[0]);
for(int i = 1 ; i < chars.length ; i++) {
    if(chars[i] != previous) {
        sb.append(chars[i]);
        previous = chars[i];
    }
}
String res = sb.toString();

这篇关于如何在Java中删除字符串中的相邻重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆