首页 > 应用开发 > Java > 寻找字符串中第一次出现的字符
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
注意看,字符要区分大小写,所以这道题难度就上去一点了,但是还是简单的。一共有两种解题方法,一种是利用字典去统计字符出现的次数,一种是利用数组去统计字符出现的次数
using System.Collections.Generic;
class Solution
{
public int FirstNotRepeatingChar(string str)
{
// write code here
Dictionary<char, int> dic = new Dictionary<char, int>();
for(int i=0;i<str.Length;i++)
{
if(dic.ContainsKey(str[i]))
{
dic[str[i]]++;
}
else
dic.Add(str[i],1);
}
for(int i=0;i<str.Length;i++)
{
if(dic[str[i]]==1)
return i;
}
return -1;
}
}
using System.Collections.Generic;
class Solution
{
public int FirstNotRepeatingChar(string str)
{
// write code here
int []a=new int[26];//存储小写字母的出现次数
int []b=new int[26];//存储大写字母的出现次数
for(int i=0;i<str.Length;i++)
{
if(str[i]>='a')
a[str[i]-'a']++;
else
b[str[i]-'A']++;
}
for(int i=0;i<str.Length;i++)
{
if((str[i]>='a' && a[str[i]-'a']==1) || (str[i]<'a' && b[str[i]-'A']==1) )
return i;
}
return -1;
}
}
文章来源:CSDN 糟糕点师
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69991606/viewspace-2745194/ ,如需转载,请注明出处,否则将追究法律责任。