剑指Offer(Java版)第三十九题:在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符, 并返回它的位置, 如果没有则返回 -1(需要区分大小写).

/*
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,
并返回它的位置, 如果没有则返回 -1(需要区分大小写).
*/
//用Map来实现

import java.util.*;

public class Class39 {

public int FirstNotRepeatingChar(String str){
if(str == null || str.length() < 0 || str.length() > 10000){
return -1;
}
int value = 0;
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
for(int i = 0; i < str.length(); i++){
if(map.containsKey(str.charAt(i))){
value = map.get(str.charAt(i));
map.put(str.charAt(i), ++value);
}else{
map.put(str.charAt(i), 1);
}
}
for(int i = 0; i < str.length(); i++){
if(map.get(str.charAt(i)) == 1){
return i;
}
}
return -1;
}

public void test(){
String a = "acbccccccca";
System.out.print(FirstNotRepeatingChar(a));
}


public static void main(String[] args) {
// TODO Auto-generated method stub
Class39 c = new Class39();
c.test();

}

}

猜你喜欢

转载自www.cnblogs.com/zhuozige/p/12518296.html