[LeetCode] NO. 387 First Unique Character in a String
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] NO. 387 First Unique Character in a String相关的知识,希望对你有一定的参考价值。
[题目]
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.
[题目解析] 根据题意,思路比较简单,遍历字符串,用map存储对应字符以及出现次数,再次遍历原字符串,当出现第一个出现一次的字符时,返回对应的index即可,考虑到Note中提示的字符串只考虑小写字母组成的情况,可以用一个26位的数组表示map结构,代码如下。
public int firstUniqChar(String s) { if(null == s || 0 == s.length() ) return -1; int[] hash = new int[26]; char[] array = s.toCharArray(); for(int i = 0; i < array.length; i++){ int num = array[i] - ‘a‘; hash[num]++; } for(int i = 0; i < array.length; i++){ int num = array[i] - ‘a‘; if(hash[num] == 1){ return i; } } return -1; }
以上是关于[LeetCode] NO. 387 First Unique Character in a String的主要内容,如果未能解决你的问题,请参考以下文章
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