Contents

Characters that appear only once (with.Java)

   Feb 27, 2024     2 min read

This article looks into the “character that appears only once” issue.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to get to know myself.

Let’s look at the problem first.

problem

The string s is given as a parameter.

Complete the solution function to return a string that sorts alphabetically the characters that appear only once in s.

If there are no characters that appear only once, an empty string is returned.

Restrictions

  • 0 < length of s < 1,000
  • s consists of lowercase letters only.

Input/Output Example

sresult
“abcabcadc”“d”
“abdc”“abcd”
“hello”“eho”

My solution to the problem

import java.util.*;

class Solution {
     public String solution(String s) {
         String answer = "";
         String[] strArr = s.split("");
         int count;
         Arrays.sort(strArr);

         for(String str : strArr){
             count = 0;

             for(int i = 0; i < strArr.length; i++){
                 if(strArr[i].equals(str)){
                     count++;
                 }
             }

             if(count == 1){
                 answer += str;
             }
         }
         return answer;
     }
}

Solution explanation

  • First, declare answer, which is an empty string. Then, the given string is divided into individual characters and stored in the strArr array. And then sort the strArr array in ascending order.
  • Use the for-each statement to perform the following for each element, str, of the strArr array.
  • Initialize the count variable to 0.
  • Use the for statement to traverse the strArr array and compare the current element and str for equality. If they are equal, increment count.
  • Add the character to the answer only if count is 1, that is, if the current character is not duplicated.
  • Returns an answer when all iterations are complete. Therefore, the solution method returns a new string consisting of non-duplicate characters from the given string.