题目
在一个长为 字符串中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
数据范围:0 \le n \le 100000≤n≤10000,且字符串只有字母组成。
要求:空间复杂度 O(n)O(n),时间复杂度 O(n)O(n)
代码
public class Solution {
public int FirstNotRepeatingChar(String str) {
int[] count=new int[58];
for(char c:str.toCharArray())
{
count[c-'A']++;
}
for(int i=0;i<str.length();i++)
{
if(count[str.charAt(i)-'A']==1)
return i;
}
return -1;
}
}
反思
我傻了,最开始想着时间复杂度是O(n),就想着如何通过一次遍历就能完成,但是忽略了可以遍历多次啊,多次也是时间复杂度O(n)。