Java:打印字符串中的唯一字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40899915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:58:16  来源:igfitidea点击:

Java: Print a unique character in a string

javastringcharacterunique

提问by Dextra

I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.

我正在编写一个程序,它将打印字符串中的唯一字符(通过扫描仪输入)。我已经创建了一个尝试完成此操作的方法,但我不断获得不重复的字符,而不是字符串独有的一个(或多个)字符。我只想要独特的字母。

Here's my code:

这是我的代码:

import java.util.Scanner;
public class Sameness{
   public static void main (String[]args){
   Scanner kb = new Scanner (System.in); 
     String word = "";

     System.out.println("Enter a word: ");
     word = kb.nextLine();

     uniqueCharacters(word); 
}

    public static void uniqueCharacters(String test){
      String temp = "";
         for (int i = 0; i < test.length(); i++){
            if (temp.indexOf(test.charAt(i)) == - 1){
               temp = temp + test.charAt(i);
         }
      }

    System.out.println(temp + " ");

   }
}            

And here's sample output with the above code:

这是带有上述代码的示例输出:

Enter a word: 
nreena
nrea 

The expected output would be: ra

预期输出将是: ra

采纳答案by lmiguelvargasf

Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:

根据您所需的输出,您必须替换最初已添加的字符,然后再复制它,因此:

public static void uniqueCharacters(String test){
    String temp = "";
    for (int i = 0; i < test.length(); i++){
        char current = test.charAt(i);
        if (temp.indexOf(current) < 0){
            temp = temp + current;
        } else {
            temp = temp.replace(String.valueOf(current), "");
        }
    }

    System.out.println(temp + " ");

}

回答by Naman

Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an elseas follows :

虽然要接近解决方案,我建议您尝试使用更好的数据结构,而不仅仅是字符串。然而,您可以简单地修改您的逻辑以使用else如下删除现有的重复项:

public static void uniqueCharacters(String test) {
        String temp = "";
        for (int i = 0; i < test.length(); i++) {
            char ch = test.charAt(i);
            if (temp.indexOf(ch) == -1) {
                temp = temp + ch;
            } else {
                temp.replace(String.valueOf(ch),""); // added this to your existing code
            }
        }

        System.out.println(temp + " ");

    }

回答by Gendarme

I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.

我会将字符串的所有字符存储在一个数组中,您将遍历该数组以检查当前字符是否多次出现在那里。如果没有,则将其添加到 temp.

public static void uniqueCharacters(String test) {
    String temp = "";
    char[] array = test.toCharArray();
    int count; //keep track of how many times the character exists in the string

    outerloop: for (int i = 0; i < test.length(); i++) {
        count = 0; //reset the count for every new letter
        for(int j = 0; j < array.length; j++) {
            if(test.charAt(i) == array[j])
                count++;
            if(count == 2){
                count = 0;
                continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
            }
        }
        temp += test.charAt(i);
        System.out.println("Adding.");
    }    
    System.out.println(temp);
}

I have added comments for some more detail.

我已经添加了一些更详细的评论。

回答by Bohemian

How about applying the KISS principle:

如何应用 KISS 原则:

public static void uniqueCharacters(String test) {
    System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}

回答by shanbhagsv

import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String[] args)
{

Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
 try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
    }
    }
    catch(Exception e)
    {
    System.out.println("error");
    }
}
}

回答by rajesh

The accepted answer will not pass all the test case for example

例如,接受的答案不会通过所有测试用例

input -"aaabcdd"

输入 -"aaabcdd"

desired output-"bc"
but the accepted answer will give -abc

所需的输出 -"bc"
但接受的答案将给出 -abc

because the character a present odd number of times.

因为这个字符出现了奇数次。

Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.

在这里,我使用 ConcurrentHasMap 来存储字符和字符出现的次数,如果出现次数超过一次,则删除该字符。

import java.util.concurrent.ConcurrentHashMap;

public class RemoveConductive {

    public static void main(String[] args) {

        String s="aabcddkkbghff";

        String[] cvrtar=s.trim().split("");

        ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
        for(int i=0;i<cvrtar.length;i++){
            if(!hm.containsKey(cvrtar[i])){
                hm.put(cvrtar[i],1);
            }
            else{
                 hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
            }
        }
        for(String ele:hm.keySet()){
            if(hm.get(ele)>1){
                hm.remove(ele);
            }
        }
        for(String key:hm.keySet()){
            System.out.print(key);
        }
    }  
}

回答by DareDevil

If you don't want to use additional space:

如果您不想使用额外的空间:

    String abc="developer";

    System.out.println("The unique characters are-");

    for(int i=0;i<abc.length();i++)
    {
        for(int j=i+1;j<abc.length();j++)
        {
            if(abc.charAt(i)==abc.charAt(j))
                abc=abc.replace(String.valueOf(abc.charAt(j))," ");
        }
    }   
    System.out.println(abc);

Time complexity O(n^2) and no space.

时间复杂度 O(n^2) 并且没有空间。

回答by Parviz Makari

how about this :)

这个怎么样 :)

for (int i=0; i< input.length();i++)
    if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
        System.out.println(input.charAt(i) + "  is unique");

回答by RathanaKumar

This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.

此字符串算法用于打印字符串中的唯一字符。它在 O(n) 运行时运行,其中 n 是字符串的长度。它仅支持 ASCII 字符。

static String printUniqChar(String s) {
    StringBuilder buildUniq = new StringBuilder();
    boolean[] uniqCheck = new boolean[128];
    for (int i = 0; i < s.length(); i++) {
        if (!uniqCheck[s.charAt(i)]) {
            uniqCheck[s.charAt(i)] = true;
            if (uniqCheck[s.charAt(i)])
                buildUniq.append(s.charAt(i));
        }
    }

回答by Soudipta Dutta

This is an interview question. Find Out all the unique characters of a string. Here is the complete solution. The code itself is self explanatory.

这是一道面试题。找出字符串的所有唯一字符。这是完整的解决方案。代码本身是不言自明的。

public class Test12 {
    public static void main(String[] args) {
        String a = "ProtijayiGiniGina";

        allunique(a);
    }

    private static void allunique(String a) {
        int[] count = new int[256];// taking count of characters
        for (int i = 0; i < a.length(); i++) {
            char ch = a.charAt(i);
            count[ch]++;
        }

        for (int i = 0; i < a.length(); i++) {
            char chh = a.charAt(i);
            // character which has arrived only one time in the string will be printed out
            if (count[chh] == 1) {
                System.out.println("index => " + i + " and unique character => " + a.charAt(i));

            }
        }

    }// unique

}

In Python :

在 Python 中:

def firstUniqChar(a):
    count = [0] *256
    for i in a: count[ord(i)] += 1
    element = ""

    for item in a:
        if (count[ord(item)] == 1):
            element = item;
            break;
    return element        


a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P