LeetCode_387. First Unique Character in a String
Posted 邓戈麟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode_387. First Unique Character in a String相关的知识,希望对你有一定的参考价值。
387. First Unique Character in a String
Easy
Given a string, find the first non-repeating character in it and return it‘s index. If it doesn‘t exist, return -1.
Examples:
s = "leetcode" return 0. s = "loveleetcode", return 2.
Note: You may assume the string contain only lowercase letters.
package leetcode.easy; public class FirstUniqueCharacterInAString { public int firstUniqChar(String s) { java.util.HashMap<Character, Integer> count = new java.util.HashMap<Character, Integer>(); int n = s.length(); // build hash map : character and how often it appears for (int i = 0; i < n; i++) { char c = s.charAt(i); count.put(c, count.getOrDefault(c, 0) + 1); } // find the index for (int i = 0; i < n; i++) { if (count.get(s.charAt(i)) == 1) return i; } return -1; } @org.junit.Test public void test() { System.out.println(firstUniqChar("leetcode")); System.out.println(firstUniqChar("loveleetcode")); } }
以上是关于LeetCode_387. First Unique Character in a String的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode-387 First Unique Character in a String
#Leetcode# 387. First Unique Character in a String
LeetCode387. First Unique Character in a String
LeetCode - 387. First Unique Character in a String