首页 > 解决方案 > 使用循环删除所有相邻的重复项

问题描述

我正在尝试解决这个问题。我见过其他涉及列表和使用递归的解决方案,但我有兴趣学习如何使用循环解决这个问题,但我似乎无法获得正确的输出。 (即没有正则表达式,没有元组,没有字符串方法等)

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)

注释掉的部分是使整个程序循环通过以验证它们不再重复。

标签: pythonpython-3.x

解决方案


    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

推荐阅读