方案一:用52的数组来存,之后要在找到的位置中找个最小的
import java.util.*;
public class Solution {
public int FirstNotRepeatingChar(String str) {
if(str.length()==0)
return -1;
int a[]=new int[52];
char c[]=str.toCharArray();
int index=0;
for(int i=0;i<c.length;i++){
if(c[i]<='Z'){
index = c[i]-'A';
a[index]=a[index]+1;
}
else{
index=c[i]-'a'+26;
a[index]=a[index]+1;
}
}
int temp=0;
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0;i<a.length;i++){
if(a[i]==1)
for (int j = 0; j < c.length; j++)
if (i < 26) {
temp =c[j]-'A';
if (temp== i) {
list.add(j);
break;
}
}
else {
temp =c[j]-'a'+26;
if(temp==i) {
list.add(j);
break;
}
}
}
if(list.isEmpty())
return -1;
else
return Collections.min(list);
}
}
import java.util.*;public class Solution {public int FirstNotRepeatingChar(String str) {if(str.length()==0)return -1;
int a[]=new int['z'-'A'];
char c[]=str.toCharArray();
for(int i=0;i<c.length;i++)
a[c[i]-'A']=a[c[i]-'A']+1;
for(int i=0;i<c.length;i++)
if(a[c[i]-'A']==1)
return i;
return -1;
}
}
//方案二:一样的道理
public class Solution {
public int FirstNotRepeatingChar(String str) {
if(str.length()==0)
return -1;
int a[]=new int['z'-'A'+1];
char c[]=str.toCharArray();
for(int i=0;i<c.length;i++)
a[c[i]-'A']+=1;
for(int i=0;i<c.length;i++)
if(a[c[i]-'A']==1)
return i;
return -1;
}
}
//方案三
import java.util.*;
public class Solution {
public int FirstNotRepeatingChar(String str) {
if(str.length()==1)
return -1;
Hashtable hash =new Hashtable();
char c[]=str.toCharArray();
for(int i=0;i<c.length;i++){
if(hash.get(c[i])==null)
hash.put(c[i],1);
else
hash.put(c[i],(int)hash.get(c[i])+1);
}
for(int i=0;i<c.length;i++)
if((int)hash.get(c[i])==1)
return i;
return -1;
}
}