码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode_387. First Unique Character in a String

时间:2019-11-17 10:59:59      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:rac   dex   and   find   efault   only   ase   appears   leetcode   

 

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

标签:rac   dex   and   find   efault   only   ase   appears   leetcode   

原文地址:https://www.cnblogs.com/denggelin/p/11875310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!