例如,String s = "abdcab",第一個出現一次的字符是d。
法1:
對於每一個元素,從頭開始遍歷有沒有重複的,兩重for循環。
法2:
從第一個元素開始,我查找此元素後面的每一個元素,如果重複,則將這些重複的設爲‘\n’,這樣我就不用判斷這些爲‘\n’的元素了,如果沒有則肯定是第一次出現的,記住要設置標誌位。
public static char find(String s)
{
char key = '\n';
char[] ch = s.toCharArray();
int i = 0, j = 0;
for(i = 0; i < ch.length; i++)
{
char now = ch[i];
boolean flag = false;
if(now != '\n')
{
for(j = i + 1; j < ch.length; j++)
{
if(ch[j] == now)
{
flag = true;
ch[j] = '\n';
}
}
if(!flag)
return now;
}
}
return key;
}
法3:利用LinkedHashMap,統計次數。
public static char find(String s)
{
char key = '\n';
char[] ch = s.toCharArray();
LinkedHashMap<Character,Integer> map = new LinkedHashMap<Character,Integer>();
Set<Character> set = map.keySet();
int i = 0, j = 0;
for(i = 0; i < ch.length; i++)
{
if(set.contains(ch[i]))
{
j = map.get(ch[i]);
j++;
map.put(ch[i],j);
}
else
map.put(ch[i], 1);
}
for(Map.Entry<Character, Integer> entry : map.entrySet())
{
key = entry.getKey();
int value = entry.getValue();
if(value == 1)
return key;
}
return key;
}
法4:利用HashMap
public static Character findFirst(String s) { if(s == null) return null; char[] ch = s.toCharArray(); Map<Character,Integer> map = new HashMap<Character,Integer>(); for(int i = 0; i<ch.length; i++) { if(map.get(ch[i])==null) { map.put(ch[i], 1); } else { int count = map.get(ch[i]); count++; map.put(ch[i], count); } } for(int i = 0; i<ch.length; i++) { if(map.get(ch[i])==1) { return ch[i]; } } return null; }