387. First Unique Character in a String

   public int firstUniqChar(String s) {
        Set<Character> str = new HashSet<Character>();
        int i = 0;
        
        while (!str.contains(s.charAt(i))) {
            str.add(s.charAt(i));
            i++;
        }
        
        return i;
    }
   public int firstUniqChar(String s) {
        Map<Character, Integer> str = new HashMap<Character, Integer>();
        int i = 0;

        while (!str.containsKey(s.charAt(i))) {
            str.put(s.charAt(i), i);
            i++;
        }

        return str.get(s.charAt(i));
    }
   public int firstUniqChar(String s) {
        Map<Character, Integer> str = new HashMap<Character, Integer>();
        
        for (int i = 0; i < s.length(); i++) {
            if (str.containsKey(s.charAt(i))) {
                str.replace(s.charAt(i), 2);
            } else {
                str.put(s.charAt(i), 1); 
            }
        }
        
        for (int j = 0; j < s.length(); j++) {
            if (str.get(s.charAt(j)) == 1) {
                return j;
            }
        }
        return -1;
    }

좋은 웹페이지 즐겨찾기