Home Ask Login Register

Developers Planet

Your answer is one click away!

user3525412 February 2016

Knowing how many repeat the letters in the String

i have an interview Question which is Knowing repeat the letters in the String i solve it like this

String str = "my name is Java Developer";
    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        for (int j = 0; j < str.length(); j++) {
            if (str.charAt(i) == str.charAt(j)) {
                count = count + 1;

        System.out.print(count + "  ");
        count = 0;

but my problem was 1 - avoid the space from count 2-there is repeated character counted like m in 'my' and m in 'name' i don't want to repeat the count for the characters 3- i want to solve it in another way plus this one

thank you ,,


ctst February 2016

Why don't you use maps (from Character to Integer)?

Hence you won't need double for-loops and it solves your double counting.

But since it is an interview question I hesitate to give you the code.

RYS221 February 2016

1- You could use a token delimiter to remove the spaces before counting the characters in the string 2- you could have n integer array A of size 26, where the index 0 -25 each represent corresponding alphabets i.e 0-A 1-B. Every time a letter is encountered then the A[char value of letter - 'A'] is incremented to 1. Then the counter is only incremented if the value at A[letter] is 0.

Post Status

Asked in February 2016
Viewed 2,331 times
Voted 4
Answered 2 times


Leave an answer

Quote of the day: live life