(劍指offer)第一個只出現一次的字元
阿新 • • 發佈:2018-12-07
時間限制:1秒 空間限制:32768K 熱度指數:200407
本題知識點: 字串
題目描述
在一個字串(0<=字串長度<=10000,全部由字母組成)中找到第一個只出現一次的字元,並返回它的位置, 如果沒有則返回 -1(需要區分大小寫).
思路1(Map)
import java.util.*;
public class Solution {
public int FirstNotRepeatingChar(String str) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(int i = 0; i < str.length(); i++){
if(map.containsKey(str.charAt(i))){
map.put(str.charAt(i), map.get(str.charAt(i))+1);
}else{
map.put(str.charAt(i), 1);
}
}
Iterator it = map.entrySet( ).iterator();
Integer index = str.length();
while(it.hasNext()){
Map.Entry entry = (Map.Entry)it.next();
Character key = (Character)entry.getKey();
Integer value = (Integer)entry.getValue();
if(value == 1){
if(str.indexOf (key)<index){
index = str.indexOf(key);
}
}
}
if(index < str.length()){
return index;
}else{
return -1;
}
}
}
思路2(ArrayList)
import java.util.*;
public class Solution {
public int FirstNotRepeatingChar(String str) {
ArrayList<Character> list = new ArrayList<Character>();
ArrayList<Integer> index = new ArrayList<Integer>();
for(int i = 0; i < str.length(); i++){
Character c = str.charAt(i);
if(list.contains(c)){
int x = list.indexOf(c);
int cnt = index.get(x);
index.set(x, cnt+1);
}else{
list.add(c);
index.add(1);
}
}
for(int i = 0; i < index.size(); i++){
if(index.get(i) == 1){
return str.indexOf(list.get(i));
}
}
return -1;
}
}