【问题标题】:Java: Print a unique character in a stringJava:打印字符串中的唯一字符
【发布时间】:2017-04-15 10:59:34
【问题描述】:

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

这是我的代码:

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 + " ");

   }
}            

这是上面代码的示例输出:

Enter a word: 
nreena
nrea 

预期的输出是:ra

【问题讨论】:

  • 'nreena' 的预期输出是什么?
  • 但是e 是重复的,你仍然会得到它。期望的输出是ra吗?
  • 无论如何,我会做类似char[] array = test.toCharArray(); 之类的操作,然后为test 中的每个字母循环遍历array,如果没有匹配项,请执行temp = temp + test.charAt(i);
  • 是的,所需的输出是“ra”。
  • 一旦你添加了一个字符,你并没有在发现它多次出现时删除现有的字符。

标签: java string character unique


【解决方案1】:

根据你想要的输出,你必须替换一个最初已经添加的字符,当它以后有重复时,所以:

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 + " ");

}

【讨论】:

  • 高效
  • 非常感谢!
  • 是否需要else块..?
  • @Suree,这是必需的。基本上,else 块正在删除一个最初被视为唯一的字符,但一旦发现重复的字符就应该删除。
  • @lmiguelvargasf,实际上 else 阻止删除 temp 中每第二个出现的字符。 temp.indexOf(current) 也在检查最初在临时字符串中被视为唯一的字符。因此,不需要 else 块。我已经检查过了。
【解决方案2】:

虽然要找到解决方案,但我建议您尝试使用更好的数据结构,而不仅仅是字符串。然而,您可以使用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 + " ");

    }

【讨论】:

  • 看起来很有趣,但我的答案和你的看起来几乎完全一样,只是变量的名称发生了变化。不过,我在可以使用的时候使用了这个变量,也就是说,我不会多次重复test.charAt(i)
  • 正确的不应该重复使用它。只是试图优化 OPs 代码。错过了。
【解决方案3】:

我会将字符串的所有字符存储在一个数组中,您将循环检查当前字符是否多次出现在那里。如果没有,则将其添加到 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);
}

我添加了 cmets 以获得更多细节。

【讨论】:

    【解决方案4】:

    如何应用 KISS 原则:

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

    【讨论】:

    • 与上述解决方案相比,这是执行时间最短的最佳答案。
    【解决方案5】:
    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");
        }
    }
    }
    

    【讨论】:

    • 你能补充一些解释吗?谢谢!
    • HashSet 不支持重复值我将每个字符都添加到 hashset 中,这样重复值会自动解决。
    【解决方案6】:

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

    输入-"aaabcdd"

    想要的输出-"bc"
    但接受的答案将给出 -abc

    因为角色出现奇数次。

    这里我使用 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);
            }
        }  
    }
    

    【讨论】:

      【解决方案7】:

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

          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);
      

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

      【讨论】:

        【解决方案8】:

        这个怎么样:)

        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");
        

        【讨论】:

          【解决方案9】:

          此字符串算法用于打印字符串中的唯一字符。它在 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));
                  }
              }
          

          【讨论】:

          • 不鼓励仅使用代码回答,因为它们没有为未来的读者提供太多信息,请对您所写的内容提供一些解释
          【解决方案10】:

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

          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
          
          }
          

          在 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
          

          【讨论】:

            【解决方案11】:
            public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";
            
            public static void uniqueValue (String numbers) {
                String [] str = input.split(" ");
                Set <String> unique = new HashSet <String> (Arrays.asList(str));
                System.out.println(unique);
            
                for (String value:unique) {
                    int count = 0;
                    for ( int i= 0; i<str.length; i++) {
                        if (value.equals(str[i])) {
                            count++;
                        }
                    }
                    System.out.println(value+"\t"+count);
                }
            }
            public static void main(String [] args) {
                uniqueValue(input);
            }
            

            【讨论】:

              【解决方案12】:
              public class UniqueCharactersInString {
              
              
               public static void main(String []args){
              
                  String input = "aabbcc";
                  String output = uniqueString(input);
              
                  System.out.println(output);
               }
              
               public static String uniqueString(String s){
                   HashSet<Character> uniques = new HashSet<>();
                   uniques.add(s.charAt(0));
                   String out = "";
                   out += s.charAt(0);
              
                   for(int i =1; i < s.length(); i++){
                       if(!uniques.contains(s.charAt(i))){
                           uniques.add(s.charAt(i));
                           out += s.charAt(i);
                       }
                   }
                   return out;
               }
              }
              

              这个答案有什么不足之处?它与其他答案相比如何?

              【讨论】:

              • 不鼓励仅使用代码的答案。为了帮助未来的读者,请解释一下你在做什么!
              【解决方案13】:

              根据您想要的输出,您可以用空白字符替换已经存在的每个字符。

              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);
                    } else {
                       temp.replace(String.valueOf(temp.charAt(i)), "");
                    }
               }
              
              System.out.println(temp + " ");
              

              }

              【讨论】:

                【解决方案14】:
                public void uniq(String inputString) {
                    String result = "";
                    int inputStringLen = inputStr.length();
                    int[] repeatedCharacters = new int[inputStringLen];
                    char inputTmpChar;
                    char tmpChar;
                
                    for (int i = 0; i < inputStringLen; i++) {
                        inputTmpChar = inputStr.charAt(i);
                        for (int j = 0; j < inputStringLen; j++) {
                            tmpChar = inputStr.charAt(j);
                            if (inputTmpChar == tmpChar)
                                repeatedCharacters[i]++;
                        }
                    }
                
                    for (int k = 0; k < inputStringLen; k++) { 
                        inputTmpChar = inputStr.charAt(k);
                        if (repeatedCharacters[k] == 1)
                            result = result + inputTmpChar + " ";
                    }
                
                    System.out.println ("Unique characters: " + result);
                }
                

                在第一个 for 循环中,我计算字符在字符串中重复的次数。
                在第二行中,我正在寻找重复一次的字符。

                【讨论】:

                  【解决方案15】:
                  
                  package extra;
                  
                  public class TempClass {
                  
                      public static void main(String[] args) {
                          // TODO Auto-generated method stub
                          String abcString="hsfj'pwue2hsu38bf74sa';fwe'rwe34hrfafnosdfoasq7433qweid";
                          char[] myCharArray=abcString.toCharArray();
                          TempClass mClass=new TempClass();
                  
                          mClass.countUnique(myCharArray);
                          mClass.countEach(myCharArray);
                      }
                      /**
                       * This is the program to find unique characters in array.
                       * @add This is nice.
                       * */
                      public void countUnique(char[] myCharArray) {
                          int arrayLength=myCharArray.length;
                          System.out.println("Array Length is: "+arrayLength);
                          char[] uniqueValues=new char[myCharArray.length];
                          int uniqueValueIndex=0;
                          int count=0;
                          for(int i=0;i<arrayLength;i++) {
                              for(int j=0;j<arrayLength;j++) {
                                  if (myCharArray[i]==myCharArray[j] && i!=j) {
                                      count=count+1;
                                  }
                              }
                              if (count==0) {
                                  uniqueValues[uniqueValueIndex]=myCharArray[i];
                                  uniqueValueIndex=uniqueValueIndex+1;
                                  count=0;
                              }
                              count=0;
                          }
                          for(char a:uniqueValues) {
                              System.out.println(a);
                          }
                      }
                      /**
                       * This is the program to find count each characters in array.
                       * @add This is nice.
                       * */
                      public void countEach(char[] myCharArray) {
                  
                      }
                  }
                  
                  

                  【讨论】:

                  • 添加解释以帮助用户了解问题的实际出处。
                  【解决方案16】:

                  这里 str 将是您查找唯一字符的字符串。

                  function getUniqueChars(str){
                  let uniqueChars = '';
                  for(let i = 0; i< str.length; i++){
                    for(let j= 0; j< str.length; j++) {
                      if(str.indexOf(str[i]) === str.lastIndexOf(str[j])) {
                         uniqueChars += str[i];
                       }
                     }
                   }
                   return uniqueChars;    
                  

                  }

                  【讨论】:

                    【解决方案17】:

                    步骤一: 为了找到字符串中的唯一字符,我首先从用户那里获取了字符串。 Step2: 使用java中的内置函数将输入字符串转换为charArray。 步骤 3: 考虑两个 HashSet(set1 用于存储所有字符,即使它被重复,set2 用于仅存储唯一字符。 Step4 : 对数组运行 for 循环并检查 set1 中是否不存在特定字符,然后将其添加到 set1 和 set2 中。如果该特定字符已经存在于 set1 中,则将其再次添加到 set1 但将其从 set2 中删除。(当特定字符重复奇数次时,此 else 部分很有用)。 Step5 : 现在 set2 将只有唯一字符。因此,只需打印该 set2。

                    public static void main(String[] args)
                    {
                        Scanner input = new Scanner(System.in);
                        String str = input.next();
                        char arr[] = str.toCharArray();
                        
                        HashSet<Character> set1=new HashSet<Character>();
                        HashSet<Character> set2=new HashSet<Character>();
                    
                        
                        for(char i:arr)
                        {
                            if(set1.contains(i))
                            {
                                set1.add(i);
                                set2.remove(i);
                                
                            }
                            else
                            {
                                
                                set1.add(i);
                                set2.add(i);
                            }
                        }
                        
                        System.out.println(set2); 
                    
                    }
                    

                    【讨论】:

                      【解决方案18】:
                      public static void main(String[] args) {
                          String s = "aaabcdd";
                          char a[] = s.toCharArray();
                          List duplicates = new ArrayList();
                          List uniqueElements = new ArrayList();
                          for (int i = 0; i < a.length; i++) {
                              uniqueElements.add(a[i]);
                              for (int j = i + 1; j < a.length; j++) {
                                  if (a[i] == a[j]) {
                                      duplicates.add(a[i]);
                                      break;
                                  }
                              }
                          }
                          uniqueElements.removeAll(duplicates);
                          System.out.println(uniqueElements);
                          System.out.println("First Unique : "+uniqueElements.get(0));
                      
                      }
                      

                      输出: [b,c] 第一个独特的:b

                      【讨论】:

                        【解决方案19】:
                        import java.util.*;
                        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){
                             for(int i=0;i<test.length();i++){
                                 if(test.lastIndexOf(test.charAt(i))!=i)
                                 test=test.replaceAll(String.valueOf(test.charAt(i)),"");
                             }
                          System.out.println(test);
                        }
                        
                        }
                        

                        【讨论】:

                        • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2015-06-19
                        • 1970-01-01
                        • 2017-12-04
                        • 2011-12-09
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多