题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
题解
方法1:
统计所有字符出现的次数,返回第一个次数为1的数。保存可以用数组或Map等,不多解释。
方法2:
建立两个表,第一个保存当前仅出现1次的元素,另一个保存不只一次的元素,返回表1中第一个元素。
static int firstNotRepeatingChar(String str) {
if(str.isEmpty())
{
return -1;
}
char[] arr = str.toCharArray();
List<Character> list = new ArrayList<>(); //保存出现不只1次的元素
List<Character> ans = new ArrayList<>(); //保存当前仅出现了1次的元素
for(int i=0; i<arr.length; i++)
{
Character ch = new Character(arr[i]);
if( (! list.contains(ch) ) && (! ans.contains(ch)) )
{//如果list和ans中都没有该元素,则该元素当前仅出现了1次
ans.add(ch);
}
else if(ans.contains(ch) && (!list.contains(ch)) )
{//如果ans中已经有该元素,则说明该元素出现不仅1次,将其移出ans并加入list
ans.remove(ch);
list.add(ch);
}
}
if(ans.isEmpty())
{//ans为空,则没有仅出现1次的元素
return -1;
}
else
{//ans不为空,则返回第一个元素在字符串的下标
char ch = ans.get(0);
return str.indexOf(ch);
}
}