第一次只出现一次的字符
问题陈述
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例:
1 2 3 4 5
| s = "abaccdeff" 返回 "b"
s = "" 返回 " "
|
思路分析
将字符串转为字符数组,逐个遍历存入HashMap,其他key为字符,value为:若map中没有该字符,置为true;有该字符,置为false,通过map.containsKey( )得到。
遍历map,得到第一个值为true的元素便是。
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class FirstUniqueChar { public char firstunichar(String s) { HashMap<Character,Boolean> map=new HashMap<>(); char[] res=s.toCharArray(); for(char c:res) map.put(c,!map.containsKey(c)); for(char c:res) if(map.get(c)) return c; return ' ';
} public static void main(String[] args){ String s="abass"; FirstUniqueChar firstUniqueChar=new FirstUniqueChar(); System.out.println(firstUniqueChar.firstunichar(s)); } }
|