LeetCode 387. First Unique Character in a String

Problem:

 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. 

try:

class Solution {
public int firstUniqChar(String s) {
int[] counts = new int[26];
for(int i=0;i<s.length();i++){
counts[s.charAt(i)-'a']++;
}
for(int i=0;i<counts.length;i++){
if(counts[i]==1) return i;
}

return -1;
}
}

result:

second:

import java.util.HashMap;

class Solution {
public int firstUniqChar(String s) {
HashMap<Character, Integer> map = new LinkedHashMap<Character, Integer>();
for(int i=0;i<s.length();i++){
//if(map.get((Character)s.charAt(i))==null) map.put()
Character c = s.charAt(i);
Integer int = map.get(c);
map.put(c, integer==null ? 1 : (++integer));
}

for(MapEntry entry : map){
if(entry.getValue()==1) return entry.getKey();
}

return -1;
}
}

result:

Run Code Status: Compile Error
Run Code Result:

"leetcode"

Line 10: error: not a statement

0

re-try:

import java.util.HashMap;
import java.util.Map.Entry;

class Solution {
public int firstUniqChar(String s) {
HashMap<Character, Integer> map = new LinkedHashMap<Character, Integer>();
for(int i=0;i<s.length();i++){
//if(map.get((Character)s.charAt(i))==null) map.put()
Character c = s.charAt(i);
Integer integer = map.get(c);
map.put(c, integer==null ? 1 : (++integer));
}

for(Map.Entry<Character, Integer> entry : map.entrySet()){
if(entry.getValue()==1){
return s.indexOf(entry.getKey());
}
}

return -1;
}
}

result:

分析：

re-try:

import java.util.HashSet;

class Solution {
public int firstUniqChar(String s) {
int[] counts = new int[26];
char[] charArray = s.toCharArray();
for(char c : charArray){
counts[c-'a']++;
}

HashSet<Character> set = new HashSet<Character>();
for(int i=0;i<counts.length;i++){
}

for(int i=0;i<charArray.length;i++){
if(set.contains(charArray[i])) return i;
}

return -1;
}
}

result:

conclusion:

posted @ 2018-04-28 10:18  Zhao_Gang  阅读(94)  评论(0编辑  收藏  举报