题目:
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
思路1:
暴力法,i从前向后遍历,j从i+1向后遍历,找到和当前字符str.charAt(i)=temp相同的,将此字符串中的此字符全部替换成‘&’,如果j一直到最后,没有找到和当前字符temp相同的,则返回当前字符的位置i
代码:
public class Solution {
public int FirstNotRepeatingChar(String str) {
int result = -1;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == '&'){
continue;
}
char temp = str.charAt(i);
int flag = 0;
for(int j = i+1; j < str.length(); j++){
if(str.charAt(j) == temp){
flag = 1;
str = str.replace(str.charAt(j),'&');
break;
}
}
if(flag == 0){
result = i;
break;
}
}
return result;
}
}
思路2:
借鉴了大佬们的思路
https://www.nowcoder.com/questionTerminal/1c82e8cf713b4bbeb2a5b31cf5b0417c
https://blog.csdn.net/justlikeu777/article/details/85066308
A-Z对应的ASCII码为:65-90
a-z对应的ASCII码为:97-122
字符串全由字母组成,字母区分大小写,一共由52个字母,建立一个52+7的数组,
遍历一遍字符串,每个字母对应数组的一个下标值,数组里面的值是数组下标对应字符的次数
再遍历一遍字符串,找到第一个字符对应的数组值为1的字符在字符串中的位置
代码:
public class Solution {
public int FirstNotRepeatingChar(String str) {
int result = -1;
int[] res = new int[59];
for(int i = 0; i < str.length(); i++){
res[(int)str.charAt(i) - 65] += 1; //当前字符的位置是字符的ASCII码值减去65,值就是字符的当前次数
}
for(int i = 0; i < str.length(); i++){
if(res[(int)str.charAt(i)-65] == 1){
result = i;
break;
}
}
return result;
}
}