欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > 删除连续重复字符

删除连续重复字符

2026/6/1 8:20:19 来源:https://blog.csdn.net/2301_80419036/article/details/142634562  浏览:    关键词:删除连续重复字符

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

题解,可以利用栈来实现,创建一个对象用来储存,字母以及字母的个数,最后从栈中取出元素,拼接到字符串

package 算法.栈;import java.util.*;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);String str = scanner.nextLine();
//        remove(str);System.out.println(remove(str));}public static String remove(String str) {Stack<Object> stack = new Stack<>();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 = (CharWithCount) stack.peek();if (topChar.c != c) {stack.push(new CharWithCount(c, 1));continue;}//栈顶字符跟c相同,判断栈顶字符的计数是否达到3,如果达到,则出栈,否则计数+1if (topChar.count == 2) {stack.pop();continue;}//栈顶元素跟c相同,并且满足连连消topChar.count++;}String up = "";for (int i = 0; i < stack.size(); i++) {CharWithCount a = (CharWithCount) stack.get(i);up += a.c;}return up;}public static class CharWithCount {public char c;public int count;public CharWithCount(char c, int count) {this.c = c;this.count = count;}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词