Java: Print a unique character in a string

前端 未结 17 1410
长情又很酷
长情又很酷 2021-01-03 00:03

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

17条回答
  •  误落风尘
    2021-01-03 00:30

    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 :

    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
    

提交回复
热议问题