package com.ag;
public class Test {
/**
* For a given string that only contains alphabet characters a-z, if 3 or more consecutive
* characters are identical, remove them from the string. Repeat this process until
* there is no more than 3 identical characters sitting besides each other.
* Example:
* Input: aabcccbbad
* Output:
* -> aabbbad
* -> aaad
* -> d
*/
public String removeConsecutive(String s) {
StringBuilder result = new StringBuilder();
if (s.length() >= 1) {
for (int i = 0; i < s.length(); i++) {
char currentChar = s.charAt(i);
int count = 0;
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == currentChar) {
count++;
}
}
if (count <= 2) {
result = result.append(currentChar);
}
}
}
return result.toString();
}
/**
*#Stage 2 - advanced requirement
* Instead of removing the consecutively identical characters, replace them with a
* single character that comes before it alphabetically.
* Example:
* ccc -> b
* bbb -> a
* Input: abcccbad
* Output:
* -> abbbad, ccc is replaced by b
* -> aaad, bbb is replaced by a
* -> d
*/
public String replaceConsecutive(String s) {
while (true) {
StringBuilder newString = new StringBuilder();
int count = 1;
for (int i = 1; i < s.length(); i++) {
if (i > 0 && s.charAt(i) == s.charAt(i - 1)) {
count++;
} else {
if (count >= 3) {
// 替换为前一个字母
if ((s.charAt(i - 1) - 1) == 96) {
newString.append("");
} else {
char newChar = (char) (s.charAt(i - 1) - 1);
newString.append(newChar);
}
} else {
for (int j = 0; j < count; j++) {
newString.append(s.charAt(j));
}
}
count = 1;
}
}
// 处理最后一组字符
if (count >= 3) {
char newChar = (char) (s.charAt(s.length() - 1) - 1);
newString.append(newChar);
} else {
for (int j = 0; j < count; j++) {
newString.append(s.charAt(s.length() - 1));
}
}
String newStr = newString.toString();
if (newStr.equals(s)) { // 没有变化
break;
}
s = newStr;
}
return s;
}
public static void main(String[] args) {
Test t = new Test();
String s1 = "aabcccbbad";
String s2 = "abcccbad";
System.out.println(t.removeConsecutive(s1)); // d
System.out.println(t.replaceConsecutive(s2)); // d
}
}
超过三个连续重复的字母删除
mask哥2024-09-17 0:36
相关推荐
零千叶9 分钟前
【面试】AI大模型应用原理面试题F2E_Zhangmo2 小时前
基于cornerstone3D的dicom影像浏览器 第三章 拖拽seriesItem至displayer上显示第一张dicomYingye Zhu(HPXXZYY)3 小时前
ICPC 2023 Nanjing R L 题 Elevator坐吃山猪5 小时前
SpringBoot01-配置文件我叫汪枫5 小时前
《Java餐厅的待客之道:BIO, NIO, AIO三种服务模式的进化》yaoxtao5 小时前
java.nio.file.InvalidPathException异常程序员Xu6 小时前
【LeetCode热题100道笔记】二叉树的右视图Swift社区7 小时前
从 JDK 1.8 切换到 JDK 21 时遇到 NoProviderFoundException 该如何解决?笑脸惹桃花7 小时前
50系显卡训练深度学习YOLO等算法报错的解决方法阿维的博客日记7 小时前
LeetCode 48 - 旋转图像算法详解(全网最优雅的Java算法