Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Monday

How to find the first non repeated characters from a string in java program

How to find the non repeated characters from a string in java program

This is also one of the normally asked interview question for fresher and experienced java developer. Jobberindia provides the easy solution to solve this.

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class Programming {
    
   
    public static char getFNRChar(String str) {
        Map<Character,Integer> c = new LinkedHashMap<>(str.length());
        
        for (char c : str.toCharArray()) {
            c.put(c, c.containsKey(c) ? c.get(c) + 1 : 1);
        }
        
        for (Entry<Character,Integer> ent : c.entSet()) {
            if (ent.getValue() == 1) {
                return ent.getKey();
            }
        }
        throw new RuntimeException("no matches found");
    }


    public static char getRepeatedChar(String word) {
        Set<Character> rep = new HashSet<>();
        List<Character> nonRep = new ArrayList<>();
        for (int i = 0; i < word.length(); i++) {
            char letter = word.charAt(i);
            if (rep.contains(letter)) {
                continue;
            }
            if (nonRep.contains(letter)) {
                nonRep.remove((Character) letter);
                rep.add(letter);
            } else {
                nonRep.add(letter);
            }
        }
        return nonRep.get(0);
    }



    public static char getNonRepeatedCharacter(String word) {
        HashMap<Character,Integer> sc = new HashMap<>();
        // build table [char -> count]
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (sc.containsKey(c)) {
                sc.put(c, sc.get(c) + 1);
            } else {
                sc.put(c, 1);
            }
        }
        
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (sc.get(c) == 1) {
                return c;
            }
        }
        throw new RuntimeException("exceptionnnnnnnn");
    }

}

No comments:

Post a Comment