标签:swa 查找 res use 剑指offer question current import +=
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
使用map将字符流中的每一个字符出现的次数记录下来,然后当调用FirstAppearingOnce()时,按字符流的顺序查找在map中出现的次数,如果为1,返回该字符即可。
java中,LinkedHashMap的keySet是有序的,且是插入顺序,所以直接对map进行遍历,查找到第一个value为1的字符即可。
C++
class Solution { public: //Insert one char from stringstream void Insert(char ch) { res += ch; m[ch] ++; } //return the first appearence once char in current stringstream char FirstAppearingOnce() { for(auto i:res){ if(m[i] == 1) return i; } return ‘#‘; } private: string res = ""; map<char, int> m; };
Java
import java.util.*; public class Solution { //Insert one char from stringstream public void Insert(char ch) { if(linkedHashMap.get(ch) == null) { linkedHashMap.put(ch, 1); }else { linkedHashMap.put(ch, linkedHashMap.get(ch)+1); } } //return the first appearence once char in current stringstream public char FirstAppearingOnce() { for (char key : linkedHashMap.keySet()){ if(linkedHashMap.get(key) == 1) return (char)key; } return ‘#‘; } //@SuppressWarnings("unused") private Map<Character,Integer> linkedHashMap = new LinkedHashMap<>(); }
剑指Offer-54.字符流中第一个不重复的字符(C++/Java)
标签:swa 查找 res use 剑指offer question current import +=
原文地址:https://www.cnblogs.com/silentteller/p/12098395.html