Monday, February 1, 2016

First Repeated , Non-Repeated Character in a String

First Repeated , Non-Repeated Character in a String

public class FirstRepeatedNonRepeatedChar {

            public static void main(String[] args) {
                        System.out.println("Enter String");
                        Scanner scan = new Scanner(System.in);
                        String inputString = scan.next();
                        firstRepeatedNonRepeatedChar(inputString);
                        scan.close();
            }

            public static void firstRepeatedNonRepeatedChar(String inputString) {
                        // Creating a HashMap containing char as a key and occurrences as a
                        // value
                        HashMap<Character, Integer> map = new HashMap<>();
                        // Converting String to Array
                        char[] charArray = inputString.toCharArray();
                        // Checking each char of strArray... for new characters, always enter
                        // in else part
                        for (char c : charArray) {
                                    if (map.containsKey(c))
                                                map.put(c, map.get(c) + 1);
                                    else
                                                map.put(c, 1);
                        }
                        System.out.println("Map is "+map);
                        for (char c : charArray) {
                                    if (map.get(c) > 1) {
                                                System.out.println("First Repeated Character in" + inputString
                                                                        + "is " + c);
                                                break;
                                    }
                        }
                        for (char c : charArray) {
                                    if (map.get(c) == 1) {
                                                System.out.println("First Non-Repeated Character in"
                                                                        + inputString + "is " + c);
                                                break;
                                    }
                        }
            }
}


Output :

Enter String
Paras
Map is {s=1, r=1, P=1, a=2}
First Repeated Character in Paras is a

First Non-Repeated Character in Paras is P

No comments:

Post a Comment