在字符串中删除重复的字符

3
我需要编写一个静态方法,它以一个字符串作为参数,并返回一个新的字符串,该字符串通过替换每个重复相邻字母的实例而获得,但不使用正则表达式。例如,如果我输入“maaaakkee”作为字符串,则返回“make”。 我已经尝试了以下代码,但似乎没有显示最后一个字符。 这是我的代码:
import java.util.Scanner;
public class undouble {
    public static void main(String [] args){
        Scanner console = new Scanner(System.in);
        System.out.println("enter String: ");
        String str = console.nextLine();
        System.out.println(removeSpaces(str));
    }
public static String removeSpaces(String str){
    String ourString="";
    int j = 0;
    for (int i=0; i<str.length()-1 ; i++){
        j = i+1;
        if(str.charAt(i)!=str.charAt(j)){
            ourString+=str.charAt(i);
        }

    }

    return ourString;
    }
}

尝试使用正则表达式。 - lavrik
str.charAt(i)!=str.charAt(j) 怎么可能是真的? - Noel Yap
@lavrik 由于这似乎是入门级的内容,我怀疑提问者不知道如何使用正则表达式... - ryanlutgen
即使问题中的第一个字母出现在四个单词中,但它仍然大写,这表明这是从课程作业中复制并粘贴的事实。 - Ross Drew
@Vizkos 这可能是开始学习的原因 :) - lavrik
13个回答

43
你可以使用正则表达式来实现。例如:
String input = "ddooooonnneeeeee";
System.out.println(input.replaceAll("(.)\\1{1,}", "$1"));

输出:

done

模式解释:

  • "(.)\\1{1,}" 表示任何字符(添加到第一组)后面至少跟着一次它自己。
  • "$1" 引用第一组的内容。

2
哎呀,你比我快了。Java正则表达式教程讲解了如何使用正则表达式的好方法。 - Justin
4
正则表达式很好,但为什么要用 {1,} 而不是 + 呢? - Pshemo
1
谢谢,不幸的是我们仍然不能使用这样的表达方式,我需要坚持使用for循环。但是这是很好的信息,我会把它加入到我的笔记中 :) - abedzantout
2
@Predator44,不用客气!很抱歉听到你不能使用它 :( - Mena
1
@Pshemo 谢谢。顺便说一下,你完全可以使用 +。不确定为什么我最终使用了 {1,},但是在这种情况下它在本质上是等效的。 - Mena
显示剩余7条评论

4

也许:

for (int i=1; i<str.length() ; i++){
    j = i+1;
    if(str.charAt(i)!=str.charAt(j)){
        ourString+=str.charAt(i);
    }
}

除非我将str.lenthg()替换为str.lenthg()-1,否则会出现错误。 - abedzantout
  1. 字符从 0length-1 进行索引
  2. 如果你只将两个不相等的字符中的左字符添加到结果中,则在情况 "abb" 中,你将跳过 "b"
  3. 不要在循环中使用 += 操作符来连接字符串,而是在循环之前创建一个 StringBuilder,并在循环内部使用 append(additionalPart) 将其添加到其中。然后可以使用 toString 方法获取结果。
- Pshemo

0

如果您无法使用replace或replaceAll,这里有一个替代方案。时间复杂度为O(2n),空间复杂度为O(N),创建字符串的时间复杂度为O(N)。它会将字符串中所有重复的字符删除,并将它们放入一个stringbuilder中。

输入:abcdef,输出:abcdef

输入:aabbcdeef,输出:cdf

private static String remove_repeated_char(String str)
{
    StringBuilder result = new StringBuilder();
    HashMap<Character, Integer> items = new HashMap<>();

    for (int i = 0; i < str.length(); i++)
    {
        Character current = str.charAt(i);
        Integer ocurrence = items.get(current);
        if (ocurrence == null)
            items.put(current, 1);
        else
            items.put(current, ocurrence + 1);
    }

    for (int i = 0; i < str.length(); i++)
    {
        Character current = str.charAt(i);
        Integer ocurrence = items.get(current);
        if (ocurrence == 1)
            result.append(current);
    }
    return result.toString();
}

0
public class RepeatedChar {

    public static void main(String[] args) {
        String rS = "maaaakkee";
        String outCome= rS.charAt(0)+"";
        int count =0;
        char [] cA =rS.toCharArray();
        for(int i =0; i+1<cA.length; ++i) {
            if(rS.charAt(i) != rS.charAt(i+1)) {
                outCome += rS.charAt(i+1);
            }
        }

        System.out.println(outCome);
    }

}

0

输入AABBBccDDD,输出BD 输入ABBCDDA,输出C

    private String reducedString(String s){
    char[] arr = s.toCharArray();
    String newString = "";
    Map<Character,Integer> map = new HashMap<Character,Integer>();
    map.put(arr[0],1);
    for(int index=1;index<s.length();index++)
    {
        Character key = arr[index];   
        int value;
        if(map.get(key) ==null)
        {
            value =0;
        }
        else 
        {
            value = map.get(key);
        }

        value = value+1;
        map.put(key,value);
    }
    Set<Character> keyset = map.keySet();

    for(Character c: keyset)
    {
        int value = map.get(c);

        if(value%2 !=0)
        {
            newString+=c;
        }
    }

    newString = newString.equals("")?"Empty String":newString;
    return newString;
}

0
public class RemoveDuplicateCharecterInString {
    static String input = new String("abbbbbbbbbbbbbbbbccccd");
    static String output = "";
    public static void main(String[] args)
 {
        // TODO Auto-generated method stub

        for (int i = 0; i < input.length(); i++) {
            char temp = input.charAt(i);
            boolean check = false;

            for (int j = 0; j < output.length(); j++) {
                if (output.charAt(j) == input.charAt(i)) {
                    check = true;
                }
            }
            if (!check) {
                output = output + input.charAt(i);
            }
        }
        System.out.println("  " + output);
    }
}

答案:abcd

0

编写Java程序以删除重复字符:

package replace;

public class removingrepeatedcharacters 

{

public static void main(String...args){
        int i,j=0,count=0;

        String str="noordeen";
        String str2="noordeen";
        char[] ch=str.toCharArray();
        for(i=0;i<=5;i++)
        {
            count=0;
            for(j=0;j<str2.length();j++)
            {
            if(ch[i]==str2.charAt(j))
            {
                count++;
                System.out.println("at the index "+j +"position  "+ch[i]+    "+ count is"+count);
                if(count>=2){
                    str=str2;
                    str2=str.replaceFirst(Character.toString(ch[j]),Character.toString(' '));
            }

                System.out.println("after replacing    "          +str2);   

            }

            }




        }

    }

}

0
String outstr = "";
String outstring = "";
for(int i = 0; i < str.length() - 1; i++) {
    if(str.charAt(i) != str.charAt(i + 1)) {
        outstr = outstr + str.charAt(i);
    }
    outstring = outstr + str.charAt(i);         
}
System.out.println(outstring);

请不要仅仅发布一些代码片段作为答案,还要解释为什么这段代码有效(与问题中的代码相比)。 - Würgspaß

0
public static void remove_duplicates(String str){
    String outstr="";
    String outstring="";
    for(int i=0;i<str.length()-1;i++) {
    if(str.charAt(i)!=str.charAt(i+1)) {
        outstr=outstr+str.charAt(i);
        }
        outstring=outstr+str.charAt(i);
        }
        System.out.println(outstring);
    }

0
import java.util.*;
public class string2 {

    public static void main(String[] args) {

        //removes repeat character from array
        Scanner sc=new Scanner(System.in);
        StringBuffer sf=new StringBuffer();
        System.out.println("enter a string");
        sf.append(sc.nextLine());
        System.out.println("string="+sf);
        int i=0;

        while( i<sf.length())
        {
            int j=1+i;
            while(j<sf.length())
            {   

                if(sf.charAt(i)==sf.charAt(j))
                {
                    sf.deleteCharAt(j);
                }
                else
                {
                    j=j+1;
                }
            }
            i=i+1;
        }

        System.out.println("string="+sf);
    }
}

你可以解释一下你的代码,而不是只是把它倒在这里。它也过于复杂了——为什么要用两个循环,为什么要用StringBuffer,为什么要删除而不是复制非重复字符? - Robert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接