본문 바로가기

Algorithms/11 Coding Interview (CS Dojo)

Non-Repeating Character (Java)

Implement a function that takes a string and returns the first character that does not appear twice or more.

Example:

  • "abacc" -> 'b' ('a' appears twice, and so does 'c')
  • "xxyzx" -> 'y' ('y' and 'z' are non-repeating characters, and 'y' appears first)

If there is no non-repeating character, return null.


풀이


import java.util.*;


public class NR {

    public static void main(String[] args) {

        // NOTE: The following input values will be used for testing your solution.

        nonRepeating("abcab"); // should return 'c'

        nonRepeating("abab"); // should return null

        nonRepeating("aabbbc"); // should return 'c'

        nonRepeating("aabbdbc"); // should return 'd'

    }


    // Implement your solution below.

    public static Character nonRepeating(String s) {

        LinkedList<Character> characters = new LinkedList<>();

        List<Character> characterList = new ArrayList<>();

        Character c = null;

        for (int i = 0; i < s.length(); i++) {

            if (!characters.contains(s.charAt(i))) {

                characters.add(s.charAt(i));

            } else {

                if (!characterList.contains(s.charAt(i))) {

                    characterList.add(s.charAt(i));

                }

            }

        }

        for (int i = 0; i <characterList.size(); i++){

            int index = characters.indexOf(characterList.get(i));

            characters.remove(index);

        }

        if (characters.size() > 0) {

            c = characters.getFirst();

        }

        return c;

    }

}