简体   繁体   English

从Java中的字符串中删除相邻的重复项

[英]Remove adjacent duplicates from the string in Java

Let's say I have an input String as "aaabbaccd". 假设我有一个输入字符串作为“ aaabbaccd”。 I need to design a program which remove all the adjacent duplicates from my output. 我需要设计一个程序,从我的输出中删除所有相邻的重复项。 So taking the example of above string, the output would be : 1. First output that I would get after removing adjacent duplicates would be "aad" (Removed aabbcc from my input). 因此,以上述字符串为例,输出为:1.删除相邻重复项后,我得到的第一个输出为“ aad”(从我的输入中删除aabbcc)。 2. In the second pass, it would remove aa from my string and make my output as "d". 2.在第二遍中,它将从我的字符串中删除aa,并将我的输出显示为“ d”。

So far, what I could design the below code : 到目前为止,我可以设计以下代码:

String input="aaabbaccd";

    String[] arr=input.split("");

    int n=arr.length;
    for(int i=0;i<n;i++) {
        if(i==arr.length-1) {
            if(arr[i-1].equals(arr[i])) {
                break;
            }
            else {
                System.out.print(arr[i]+ "");
                break;
            }
        }
        if(arr[i].equals(arr[i+1])) {
            i=i+1;
            continue;
        }
        if(!arr[i].equals(arr[i+1])) {
            System.out.print(arr[i]+ "");
        }
    }

The problem with this code is that it gives me output as aad. 这段代码的问题是它给了我aad输出。 I cannot comprehend how to do the second pass on my code. 我无法理解如何对我的代码进行第二遍。 Maybe recursion is something that I need to implement in this code. 也许递归是我需要在此代码中实现的东西。 Please help me how to implement recursion in this code. 请帮助我如何在此代码中实现递归。

One lazy alternative is to use regexp for it, where the (.) part matches any character and saving it, and the \\\\1 references back to that match. 一种懒惰的替代方法是使用regexp,其中(.)部分与任何字符匹配并保存,然后\\\\1引用返回该匹配项。 I have added recursion to continue to apply the removal until string is no longer modified: 我添加了递归以继续应用删除操作,直到不再修改字符串为止:

public String removeDuplicates(String original)
{
    String reduced = original.replaceAll("(.)\\1", "");

    if(reduced.equals(original))
        // No more duplicates, return original string
        return original;
    else
        // Duplicates were removed, continue recursion...
        return removeDuplicates(reduced);
}

The behaviour is verified with: 该行为已通过以下方式验证:

@Test
public void testIt()
{
    assertThat(removeDuplicates("aaabbaccd"), is("d"));
}
public static void main(String[] args) {
        String input="aaabbaccd";
        removeDupe(input);


    }

    public static void removeDupe(String input) {
        String[] arr=input.split("");

        StringBuffer sb=new StringBuffer();
        int n=arr.length;
        for(int i=0;i<n;i++) {
            if(i==arr.length-1) {
                if(arr.length==1) {
                    sb.append(arr[i]);
                    break;
                }
                if(arr[i-1].equals(arr[i])) {
                    break;
                }
                else {
                    sb.append(arr[i]);
                    break;
                }
            }
            if(arr[i].equals(arr[i+1])) {
                i=i+1;
                continue;
            }
            if(!arr[i].equals(arr[i+1])) {
                sb.append(arr[i]);
            }
        }

        //System.out.println(sb);

        if(sb.toString().equals(input)) {
            System.out.println(sb);
        }
        else {
            removeDupe(sb.toString());
        }


    }

接下来的一支班轮怎么样?

(new LinkedHashSet<Character>("aaabbaccd".chars().mapToObj(i -> (char)i).collect(Collectors.toList()))).stream().map(e -> e.toString()).collect(Collectors.joining());

I used StringBuilder class to store string and used StringBuilder's replace() method to remove Adjacent char. 我使用StringBuilder类存储字符串,并使用StringBuilder的replace()方法删除Adjacent char。

This statement: str.replace(i,i+2,"") will actually delete adjacent chars. 该语句: str.replace(i,i+2,"")实际上将删除相邻的字符。

The core logic is written in a static method named remove() . 核心逻辑是使用名为remove()的静态方法编写的。 Note the point that I called the remove() method more than once ie str.length()/2 times. 请注意,我多次调用remove()方法,即str.length()/ 2次。 Because to remove Adjacent pair in new string we got after calling remove() each time. 因为要删除新字符串中的相邻对,所以每次调用remove()都会得到。

public class RemoveDupl12{           
 public static StringBuilder remove(StringBuilder  str){    

   for( int i=0; i<str.length()-1; i++ )

    {
        if(str.charAt(i)==str.charAt(i+1))
        { 
            str.replace(i,i+2,"");
            i++;
        }
    }
    return str;
}

public static void main(String[] args) {
     StringBuilder str=new StringBuilder("daaabbad");

     for(int i=str.length()/2;i>0;i--)
     str=remove(str);

     if(str.length()==0)
         System.out.println("Final output=empty string"+str);

     else
         System.out.println("Final output="+str);
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM