/** * 题目: * 请实现一个函数用来找出字符流中第一个只出现一次的字符。 * 例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。 * 当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。 * 如果当前字符流没有存在出现一次的字符,返回#字符。 */ import java.util.ArrayList; import java.util.HashMap; public class P243_FirstNotRepeatingChar { HashMap<Character, Integer> map = new HashMap<>(); ArrayList<Character> list = new ArrayList<>(); //Insert one char from stringstream public void Insert(char ch) { //如果哈希表中已经存在ch,则将ch的值加1 if (map.containsKey(ch)) { map.put(ch, map.get(ch) + 1); } //若哈希表中没有ch,则将其存入哈希表中,并将其值设置为1 else { map.put(ch, 1); } //将字符加入list中,以便后续遍历查找第一个只出现一次的字符 list.add(ch); } //return the first appearence once char in current stringstream public char FirstAppearingOnce() { char result = '#'; for (Character temp : list) { if (map.get(temp) == 1) { result = temp; break; } } return result; } public static void main(String[] args) { P243_FirstNotRepeatingChar test = new P243_FirstNotRepeatingChar(); test.Insert('a'); test.Insert('b'); test.Insert('a'); test.Insert('c'); test.Insert('d'); test.Insert('c'); test.Insert('b'); test.Insert('e'); char result = test.FirstAppearingOnce(); System.out.print(result); } }
剑指offer:第一个只出现一次的字符(java)
猜你喜欢
转载自blog.csdn.net/Sunshine_liang1/article/details/82850773
今日推荐
周排行