Using LinkedHashMap. Best and easy solution.


  • 0
    T
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    class FirstNonRepeatingCharInString {
    	public static void main(String[] args) {
    
    		String s = "LinkedHashMap";
    		char[] str = s.toCharArray();
    		Map<Character, Integer> map = new LinkedHashMap<>();
    
    		for (int i = 0; i < str.length; i++) {
    			if (map.containsKey(str[i])) {
    				map.put(str[i], map.get(str[i]) + 1);
    			} else
    				map.put(str[i], 1);
    		}
    		for (int i = 0; i < str.length; i++) {
    			if (map.get(str[i]) == 1) {
    				System.out.println("First Non repeating key is " + str[i]);
    				break;
    			}
    		}
    	}
    
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.