Java 计算用户给定的字符串中的唯一字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22597527/
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-13 16:44:49  来源:igfitidea点击:

Counting unique characters in a String given by the user

java

提问by user3453347

I have to write a program that counts the uniques characters in a String given by the user. For example "abc" returns 3 and "aabbccd" returns 4. I am not allow to use advanced Java classes like Map, Set, etc. I can only use arrays, Strings, for loops, while loops, if statements. I am trying to use a nested loop but am getting confused about how to write the algorithm for the second for loop.

我必须编写一个程序来计算用户给定的字符串中的唯一字符数。例如,“abc”返回 3,“aabbccd”返回 4。我不允许使用 Map、Set 等高级 Java 类。我只能使用数组、字符串、for 循环、while 循环、if 语句。我正在尝试使用嵌套循环,但对如何为第二个 for 循环编写算法感到困惑。

public static int countUniqueCharacters(String input){

String orgInput = input.toLowerCase();
        int count = 0;
        int stringLength = input.length();
        for( int i = 0; i<stringLength; i++){
            for(int j = 2; j > j-i-1; j--){
                char temp = orgInput.charAt(i);
                if (temp == orgInput.charAt(j)){
                    count++;

采纳答案by libik

It is extremely easy :)

这非常容易:)

public static int countUniqueCharacters(String input) {
    boolean[] isItThere = new boolean[Character.MAX_VALUE];
    for (int i = 0; i < input.length(); i++) {
        isItThere[input.charAt(i)] = true;
    }

    int count = 0;
    for (int i = 0; i < isItThere.length; i++) {
        if (isItThere[i] == true){
            count++;
        }
    }

    return count;
}

Example for input "aab"

输入“aab”的示例

First for-cycle goes 3 times, each time for one char.

第一个 for 循环进行 3 次,每次为一个字符。

Value of "a" is 97, so it turns isItThere[97] to true, then second "a" is involved, which is doing the same, isItThere[97] is set to true again (hence changing nothing).

"a" 的值是 97,所以它把 isItThere[97] 变成真,然后涉及第二个 "a",这是一样的,isItThere[97] 再次设置为真(因此什么都不改变)。

After that "b" is involved, value of char "b" is 98, therefore isItThere[98] is set to true.

在涉及“b”之后,字符“b”的值为98,因此isItThere[98]设置为true。

And then you have second for-cycle, where you cycle through the all isItThere array. If you find any true statement, you increment count. In our case, you find isItThere[97] and isItThere[98] as true statement, it means you increment twice and returning 2.

然后你有第二个 for 循环,在那里你循环遍历 all isItThere 数组。如果您发现任何正确的陈述,则增加计数。在我们的例子中,你发现 isItThere[97] 和 isItThere[98] 作为 true 语句,这意味着你增加了两次并返回 2。

回答by skiwi

Using Java 8 you could do the following:

使用 Java 8,您可以执行以下操作:

public static long countUniqueCharacters(String input) {
    return input.chars()
            .distinct()
            .count();
}

This creates an IntStreamof chars, then takes only distincts values and then counts the number of occurences.

这会创建一个IntStreamof chars,然后只取不同的值,然后计算出现的次数。

回答by wumpz

Here another solution:

这是另一个解决方案:

public static int countUniqueCharacters(String input) {
    String buffer = "";
    for (int i = 0; i < input.length(); i++) {
        if (!buffer.contains(String.valueOf(input.charAt(i)))) {
            buffer += input.charAt(i);
        }
    }
    return buffer.length();
}

The first occurance of each character is stored in buffer. Therefore you have of all characters one in buffer, therefore buffer.length()delivers the count you need.

每个字符的第一次出现存储在buffer. 因此,您拥有所有字符之一buffer,因此buffer.length()可以提供您需要的计数。

回答by SEGStriker

public static int countUniqueChars (String buf) {
    HashSet<Character> hash = new HashSet<>();
    buf = buf.toUpperCase();
    for (int i = 0; i < buf.length(); i++)
        hash.add(buf.charAt(i));
    return hash.size();
}

回答by Chris Sullivan

If your stuck on Java 7, you can use an ArrayList and just add unique values to it, then return the size of the ArrayList, which should always work even if the count is zero.

如果您坚持使用 Java 7,则可以使用 ArrayList 并为其添加唯一值,然后返回 ArrayList 的大小,即使计数为零,它也应该始终有效。

 import java.util.ArrayList;

 public int getUniqeCount( String arg )
 {
     ArrayList<Character> unique = new ArrayList<Character>();
     for( int i = 0; i < arg.length(); i++)
         if( !unique.contains( arg.charAt( i ) ) )
             unique.add( arg.charAt( i ) );
     return unique.size();
 }

回答by Sujeet Kumar Mehta

public static long calculateDistinctSubStringSum(String text) {
    Map<String, Integer> map = new HashMap<String, Integer>();
    char[] charAarry = text.toCharArray();
    for (int i = 0; i < charAarry.length; i++) {
        map.put(charAarry[i] + "", 1);
    }
    return map.size();

}

This is what I did to calculate but I am still looking for any fast way. If anyone knows please answer.

这就是我所做的计算,但我仍在寻找任何快速的方法。如果有人知道请回答。

回答by rashedcs

You can use HashSet collections for counting the unique elements in a string. It allow only unique element.

您可以使用 HashSet 集合来计算字符串中的唯一元素。它只允许唯一的元素。

Code Snippet

代码片段

public static int uniqueCount(String str) 
{
   HashSet<Character> al = new HashSet<Character>();
   char[] arr= str.toCharArray();
   for (int i=0; i<arr.length; i++) 
   {
      al.add(arr[i]);  
   }
   return al.size() ;
}  

Refer this link to get full code: ideone

请参阅此链接以获取完整代码:ideone

回答by gaurav agarwal

Try to see if the following code helps you:

试试看下面的代码是否对你有帮助:

String myString = "";

for(int i=0; i< word.length(); i++) {

    if(myString.indexOf(word.charAt(i)) == -1) {
        System.out.println(word.charAt(i));
        myString = myString + word.charAt(i);
    }
}
return myString.length();

回答by sachin bhaiya

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter String:");
    int length = scanner.nextInt();
    char[] ch1 =  new char[length];
    String[] input = new String[length];
    for (int i = 0; i < length; i++) {
        String userInput = scanner.next();
        input[i] = userInput;
         ch1= userInput.toCharArray();

        Arrays.sort(ch1);
         System.out.println(ch1);
    }

回答by Soudipta Dutta

Unique Characters In A String:

字符串中的唯一字符:

This is a basic Java interview subject, where the interviewer wants to check the knowledge of HashSet or indexOf(in case of Java 7) . Let's take up a question. Let's say the interview tells you to
Check if the String is unique : HashSet ensures uniqueness ,In other words , every object in the HashSet presents only once. Hence, we will use HashSet.

这是一个基本的 Java 面试题目,面试官想检查 HashSet 或 indexOf(如果是 Java 7)的知识。让我们提出一个问题。假设面试告诉你
检查字符串是否唯一:HashSet 确保唯一性,换句话说,HashSet 中的每个对象只出现一次。因此,我们将使用 HashSet。

import java.util.HashSet;
import java.util.Set;

public class Abc {
public static void main(String[] args) {
    String a = "Gini";
    String aa = a.toLowerCase();
       if(  isUnique(aa)   ) {
              System.out.println("All characters are unique");
       }else {
           System.out.println("All characters  are not unique");
       }
}
public static boolean isUnique(String a ) {
    Set< Character> set = new HashSet<>();
    char[] charArray =a.toCharArray();
    for(Character ch :charArray) {
        if(!set.add(ch)) {
            return false;
        }//if
    }//foreach
        return true;
}
}

The output in case of GINI will be : All characters are not unique

GINI 的输出将是:所有字符都不是唯一的

Now, the count of the unique characters. Here also we will use HashSet because of the uniqueness.

现在,独特字符的计数。由于唯一性,这里我们也将使用 HashSet。

import java.util.HashSet;

public class practice11 {
public static void main(String[] args) {
    String a = "Gini";
    String aa = a.toLowerCase();
    System.out.println(countUniqueCharacters(aa));  
}
public static int  countUniqueCharacters(String a) {
    char[] charArray = a.toCharArray();

    HashSet<Character> set = new HashSet<Character>();

    for(int i = 0 ; i< charArray.length ; i++) {

         set.add(charArray[i]);
    }//for
    return   set.size() ;//This will give 3
}
}

The output for Gini will be 3 (Gin will be considered) .

Gini 的输出将为 3(将考虑 Gin)。

indexOf Method : indexOf() returns the index of first occurrence of the character and then we are comparing with -1.

indexOf 方法: indexOf() 返回字符第一次出现的索引,然后我们与 -1 进行比较。

public class Abc {
public static void main(String[] args) {
    String a = "Gini";
    String aa = a.toLowerCase();
    String t = " ";
    for (int i = 0; i < aa.length(); i++) {
            int  pp =   aa.charAt(i) ;

        if(t.indexOf(aa.charAt(i))  ==  -1  ) {
            t = t + aa.charAt(i);
        }//if


    }//for

    System.out.println(t );// This will give => gin
    System.out.println(t.length()); // this will give 3
}//main
}//end

In Java 8, this is extremely easy. We just have to use chars().distinct().count(). But the return type will be long.

在 Java 8 中,这非常容易。我们只需要使用 chars().distinct().count()。但是返回类型会很长。

class Abc{
    public static void main(String[] args) {
        String a = "Gini";
        String aa = a.toLowerCase();
        System.out.println(  countUnique(aa));
    }

    private static long  countUnique(String aa) {
        // this will give 3(gin. another i will be not be counted as we have used distinct())
         return  aa.chars().distinct().count() ; 
    }
}

Another classic Interview Question : Find the First non repeating character in the String OR the First Unique Character in a String. This problem can be solved using the knowledge of HashMap.

另一个经典的面试问题:找到字符串中的第一个非重复字符或字符串中的第一个唯一字符。这个问题可以利用HashMap的知识来解决。

class Abc{
    public static void main(String[] args) {
          String a = "GinaRani" ;
// Output will be G
          System.out.println( firstNonRepeatingCharacter(a) );

    }//main
    public static Character firstNonRepeatingCharacter(String a){
      Map<Character, Integer> map = new HashMap<>();
        char[] charArray = a.toCharArray();
        for(    Character  ch   :     charArray){
               if( map.containsKey(ch)   )   {
                    map.put(ch, map.get(ch) +1 ) ;
               } else{
                   map.put(ch, 1);
               }
        }//for

        // 1st non repeating character

        for( int  i = 0 ; i < a.length(); i ++ ){
             char chh = a.charAt(i);
             if(  map.get(chh) == 1 ){
                 System.out.println("first non repeating character in the String is  : ");
                   return chh ; 
             }//if
        }//for

        return null; 

    }//firstNonRepeatingCharacter
}//end

We will do this with the help of list comprehension in Python. We are not using set() operator. In Python :

我们将借助 Python 中的列表理解来做到这一点。我们没有使用 set() 运算符。在 Python 中:

string = 'GiniGinaProtijayi'

unique = []

[ unique.append(ch)  for ch in string if ch not in unique ]
lengthofUniqueCharacters = len(unique)
print("length of Unique Characters => " ,lengthofUniqueCharacters)
print("as a list => ",unique)
print("as a string => " , ''.join(unique))

Just to print out the distinct characters in Java 8:

只是为了打印出 Java 8 中的不同字符:

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

        String aa = a.chars().distinct()
                .collect(StringBuilder::new, 
                        StringBuilder::appendCodePoint, 
                        StringBuilder::append)
                .toString();
        System.out.println(aa);//Gina

    }// main

}