Square Symbol on output


  • 0
    D

    I believe that I have the correct solution to this problem below. But my output from the 'return answer;' line is a square symbol instead of the actual char. I believe this might have something to do with the conversion from int back to char. Just not sure what is going on! Any help is much appreciated.

    class Solution {
        /**
            Idea:
            convert both into charArrays. 
            Then create an int array which is going to be of size 25, this relates to the letters of the alphabet, including 0 index
            In this array i will increase the frequency of each character in the first string, by casting from the char in the first charArray to
            int. Then do the same for the second charArray. 
            All I have to do is then check for the odd one out in the second list by comparison.
            Then cast this int back to it's equivalent char!
        */
        public char findTheDifference(String s, String t) {
            //a char to hold the answer in.
            char answer=' ';
            //convert both to charArrays
            char[] first = s.toCharArray();
            char[] second=t.toCharArray();
            //the two arrays to hold frequencies
            int[]firstArray = new int[256];//has to be 256 as it is converting into ASCII values
            int[]secondArray=new int[256];
            
            //now to put the frequencies into the above arrays
            for(char c: first){
                firstArray[(int)c]++;//increment the corresponding value in the array of integers. need to cast to int
            }
            for(char c: second){
                secondArray[(int)c]++;//increment the corresponding value in the array of integers. need to cast to int
            }
            
            //now compare and find the unique odd one out. Can use a previous solution for this
            for(int i =0; i< firstArray.length;i++){
                if(firstArray[i]== 0 && secondArray[i]== 1){//the firstArray has 0 for a frequency, yet the second has 1, Found the odd one out
                    answer=(char)secondArray[i];//so set the answer var to the char casted version of this i value of the secondArray
                }
            }
            return answer;
            
        }
    }
    

  • 0
    D

    @Demostroyer I figured out that I had answer=(char)secondArray[i];,when it should have been answer=(char)i;


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.