题目:
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置。
思路:
①一个判断。
②遍历每一个字符与其它字符是否相等,如果相等,计数加一。
③如果计数值为1,返回这个字符所在位置即可。
注意:
如果不成功时,返回值为-1。
如果某个字符只出现一次,计数值为1,因为这里没有跳过与自身的比较,计数值最小为1。
public class Solution {
public int FirstNotRepeatingChar(String str) {
if(str == null || str.length() == 0){//判断
return -1;
}
for(int i = 0 ; i < str.length() ; i ++){
int count = 0;//计数
for(int j = 0 ; j < str.length() ; j ++){
if(str.charAt(i) == str.charAt(j)){//比较
count++;
}
}
if(count == 1){
return i;
}
}
return -1;
}
}