Find the first non-repeated character in a string

前端 未结 21 1513
有刺的猬
有刺的猬 2020-12-06 03:53

I read of a job interview question to write some code for the following:

Write an efficient function to find the first nonrepeated character in a st

21条回答
  •  北海茫月
    2020-12-06 04:21

    In Java, 1)Create the Character count hashmap. For each character,if there is no value stored in the character,set it to 1. Else increment the value of the character by 1 .

    2)Then I Scanned the String for each character. Return character if the count in hashmap is 1 . If no character has count 1 ,then return null.

    package com.abc.ridhi;
    import java.util.HashMap;
    import java.util.Scanner;
    
    public class FirstNonRepeated {
    
        public static void main(String[] args) {
            System.out.println(" Please enter the input string :");
            Scanner in = new Scanner(System.in);
            String s = in.nextLine();
            char c = firstNonRepeatedCharacter(s);
            System.out.println("The first non repeated character is :  " + c);
        }
    
        public static Character firstNonRepeatedCharacter(String str) {
        HashMap map1 = new HashMap();
            int i, length;
            Character c;
            length = str.length(); 
            // Scan string and build hashmap
            for (i = 0; i < length; i++) {
                c = str.charAt(i);
                if (map1.containsKey(c)) {
                    // increment count corresponding to c
                    map1.put(c, map1.get(c) + 1);
                } else {
                    map1.put(c, 1);
                }
            }
            // Search map in order of string str
    
            for (i = 0; i < length; i++) {
                c = str.charAt(i);
                if (map1.get(c) == 1){
                    return c;
            }
            }
            return null;
        }
    }
    

提交回复
热议问题