Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 892

How to Find First Non-Repeated Character in a Given String - Java Program

$
0
0

A very popular interview question for String is “Find first non-repeated character in a given String”. As example if given string is “always” then first non-repeated character is ‘l’ as character ‘a’ is repeated. Same way if String is “net” then first non-repeated character is ‘n’.

There are many ways to solve this problem, in this post I am giving 3 solutions.

  1. If you are asked not to use any inbuilt API or data structure.
  2. Solution using LinkedHashMap.
  3. Solution using indexof() method of the String class.

Java code to find first non-repeated character in a given String

  1. Solution without using any data structure or API - If you are specifically asked not to use any Java collection or any library then you can solve it using outer and inner for loops where outer loop iterates through the string one character at a time and in inner loop you will have to compare each character of the string with the character assigned in the outer loop. In case you find a match that character is not the non-repeated one. Make sure to skip the index of the character which you are comparing otherwise you will always find the match.

    public class FirstOccurence {

    public static void main(String[] args) {
    String str = "zanzibar";

    boolean found = false;
    for(int i = 0; i < str.length(); i++){
    found = true;
    char c = str.charAt(i);
    //System.out.println("char " + c);
    for(int j = 0; j < str.length(); j++){
    //System.out.println("n-char " + str.charAt(j));
    // if found then set the boolean field as false
    // Also skip the char which is compared
    if(c == str.charAt(j) && j != i){
    found = false;
    break;
    }
    }
    if(found){
    System.out.println("Character is " + c);
    break;
    }
    }
    if(!found){
    System.out.println("No single character found");
    }

    }
    }

    Output


    Character is n
  2. Solution using LinkedHashMap - You can use LinkedHashMap to find the first non-repeated character in a String. Here LinkedHashMap is preferred over HashMap as LinkedhashMap maintains insertion order which helps to determine the first non-repeated character.

    public class FirstOccurence {

    public static void main(String[] args) {
    String str = "always";
    Character ch = findWithLinkedHashMap(str);
    if(ch != null){
    System.out.println("Character is " + ch);
    }else{
    System.out.println("No non-repeating character found");
    }


    }


    /**
    * Method to find non-repeated character using LinkedHashMap
    * @param str
    * @return
    */
    private static Character findWithLinkedHashMap(String str){
    Map<Character, Integer> charMap = new LinkedHashMap<Character, Integer>();
    for(int i = 0; i < str.length(); i++){
    Character c = str.charAt(i);
    // If found in map increment the count
    if(charMap.containsKey(c)){
    charMap.put(c, charMap.get(c) + 1);
    }else{
    charMap.put(c, 1); // First time insertion
    }
    }
    // Find the first character with count 1
    for(Entry<Character, Integer> entry : charMap.entrySet()){
    if(entry.getValue() == 1){
    return entry.getKey();
    }
    }
    return null;
    }
    }

    Output


    Character is l
  3. Solution using indexOf() method of the String class - Here logic used is indexOf() method returns the index of the first occurrence of the specified character where as lastIndexOf() method returns the index of the last occurrence of the specified character. If both indexes are equal that means the searched character is there in the string only once.

    public class FirstOccurence {

    public static void main(String[] args) {
    String str = "net";

    Character ct = findWithIndexComparison(str);

    if(ct != null){
    System.out.println("Character is " + ct);
    }else{
    System.out.println("No non-repeating character found");
    }

    }


    /**
    *
    * @param str
    * @return
    */
    private static Character findWithIndexComparison(String str){
    for(int i = 0; i < str.length(); i++){
    Character c = str.charAt(i);
    if(str.indexOf(c) == str.lastIndexOf(c)){
    return c;
    }
    }
    return null;
    }

    }

    Output


    Character is n

That's all for this topic How to Find First Non-Repeated Character in a Given String - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Count number of words in a String
  2. How to find the longest palindrome in the given String
  3. Converting string to int - Java Program
  4. If Given String Sub-Sequence of Another String - Java Program
  5. String charAt() and substring() methods in Java

You may also like -

>>>Go to Java Programs page


Viewing all articles
Browse latest Browse all 892

Trending Articles