python - 使用循环删除所有相邻的重复项
问题描述
我正在尝试解决这个问题。我见过其他涉及列表和使用递归的解决方案,但我有兴趣学习如何使用循环解决这个问题,但我似乎无法获得正确的输出。 (即没有正则表达式,没有元组,没有字符串方法等)
input: caaabbbaacdddd
expected output:empty string
input:abbabd
expected output:bd
下面是我的代码,我找到了解决这个问题的其他方法,我只是在寻找最基本的解决方案。
answer = input("enter a string: ")
new_answer = ""
#while answer != new_answer:
if answer == "":
print("goodBye!")
#break
p = ""
for c in answer:
if p != c:
new_answer += p
p = c
else:
p = c
print(new_answer)
注释掉的部分是使整个程序循环通过以验证它们不再重复。
解决方案
public class RemoveAdjacentDuplicates {
public static void main(String[] args) {
System.out.println(removeDuplicates("abbabd"));
}
public static String removeDuplicates(String S) {
char[] stack = new char[S.length()];
int i = 0;
for(int j = 0 ; j < S.length() ; j++) {
char currentChar = S.charAt(j);
if(i > 0 && stack[i-1] == currentChar) {
i--;
}else {
stack[i] = currentChar;
i++;
}
}
return new String(stack , 0 , i);
}
}
该计划的结果是:
input: caaabbbaacdddd
output:empty string
input:abbabd
output:bd
推荐阅读
- java - 我如何将语音替换为每个编辑文本
- angular - 如何在角度单元测试期间修复未定义的“无法读取属性订阅”?
- c# - 从 Godaddy 托管的网站发送电子邮件时出错
- excel - 将txt转换为xlsx时vbscript保留前导零
- javascript - 如何在 React 中动态填充列表项
- php - How to get certain words from a text with full sentences in PHP?
- excel - 这段代码有什么问题?不断收到应用程序定义的错误
- java - Firebase Android App 在一段时间后不断崩溃
- database - 从带小数点的字符串转换为NUMERIC时如何避免舍入整数?
- ajax - django 使用来自 db(sqlite) 的 xhr 更改图像