面试题50. 第一个只出现一次的字符
package leetcode; import java.util.HashMap; import java.util.HashSet; public class offer_50 { public char firstUniqChar1(String s) { HashSet<Character>set=new HashSet<Character>(); //如果存在相同的字符用空格代替 for(int i=0;i<s.length();i++) { if(!set.contains(s.charAt(i))) { set.add(s.charAt(i)); }else { s=s.replace(s.charAt(i), ' '); } } //找出第一个非空格的字符 for(int i=0;i<s.length();i++) { if(s.charAt(i)!=' ') {return s.charAt(i);} } return ' '; } public char firstUniqChar2(String s) { HashMap<Character, Integer> map=new HashMap<Character, Integer>(); //将每个字符和其数量存入map 集合中 for(int i=0;i<s.length();i++) { int count=1; if(map.containsKey(s.charAt(i))) { count=count+1; } map.put(s.charAt(i), count); } //找出集合中value第一个为1的字符 for(int i=0;i<s.length();i++) { if(map.get(s.charAt(i))==1) {return s.charAt(i);} } return ' '; } public static void main(String[] args) { // TODO Auto-generated method stub offer_50 off=new offer_50(); System.out.println(off.firstUniqChar1("aabccdeffb")); } }