LoginSignup
0
0

More than 1 year has passed since last update.

387 解答

Posted at

参考

Kevin Naughton Jr.

考え方

non repeating == unique と関連付ける。

unique -> Set or Map? Set も Map もunique なものしか収納できないので便利。

この問題はindexを求めないといけないので、key(Character),value(Integer(Index))にしたほうが楽。

解答

	public int firstUniqChar(String s) {
		Map<Character, Integer> input = new HashMap<>();
		
		for (int i = 0; i < s.length(); i++) {
			char current = s.charAt(i);
			if (!input.containsKey(current)) {
				input.put(current, i);
			} else {
				input.put(current, -1);
			}
		}

		int min = Integer.MAX_VALUE;
		for (char c : input.keySet()) {
			if (input.get(c) != -1) {
				min = Math.min(input.get(c), min);
			}
		}
		
		return min == Integer.MAX_VALUE ? -1 : min;
		

	}

豆知識

put 上書きできる

			if(map.containsKey(c)) {
				map.put(c, -1);
			}else {
				map.put(c, i);
			}

これで一つずつ取得できる

		for(char c : map.keySet()) {
			if(map.get(c) != -1) {
				min = Math.min(map.get(c), min);
			}
		}

ifの短縮

min == Integer.MAX_VALUE ? -1 : min;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0