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
相关推荐
阿里云云原生8 分钟前
Agent 不再是“玩具”!AgentScope Java 2.0 GA 发布:构建企业级分布式智能体底座4154119 分钟前
MyBatis-Plus + PostGIS 实战(四):GeoJSON 序列化与前端地图对接,全局 WKT + 局部 GeoJSON,两种格式优雅共存BIM云平台开发16 分钟前
【App.vue里跟踪页面跳转和用户ID】峥嵘life23 分钟前
Andorid 打开热点,关闭有线网,ifconfig卡死分析解决五条凪24 分钟前
简单理解 BM25 与 TF-IDF汪汪大队u28 分钟前
Zabbix 6.0 部署踩坑记:从启动失败到 Web 成功访问顺颂时绥_128 分钟前
new Set 过滤数据实战赵大仁28 分钟前
Next.js + Vercel AI SDK 实战:30 分钟搭出流式 Chat 页面HillVue31 分钟前
Token 叙事退潮,DAA 重新定义 AI 价值标准行者全栈架构师34 分钟前
【码动四季】Spring Boot 可观测性体系:Micrometer + OpenTelemetry + Grafana 全链路搭建