剑指offer——字符流中第一个不重复的字符

xiaoxiao2021-02-28  76

import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Solution { //Insert one char from stringstream public Solution() { for(int i = 0; i < 256; ++i) { hashtable[i] = -2; } } private int[] hashtable = new int[256]; private int count = 0; public void Insert(char ch) { //System.out.println(hashtable[ch]); //System.out.println("ch = " + (int)ch); if(hashtable[ch] == -2) { hashtable[ch] = count++; return; } if(hashtable[ch] != -2 && hashtable[ch] != -1) { hashtable[ch] = -1; return; } } //return the first appearence once char in current stringstream public char FirstAppearingOnce() { // System.out.println(count); // System.out.println(hashtable['g']); int res = count; int k = 0; for(int i = 0; i < 256; ++i) { if(hashtable[i] != -2 && hashtable[i] != -1) { if(res > hashtable[i]) { res = hashtable[i]; k = i; } } } if(res == count) return '#'; else return (char)k; } public static void main(String[] args) { Solution solution = new Solution(); solution.Insert('g'); System.out.println(solution.FirstAppearingOnce()); } }
转载请注明原文地址: https://www.6miu.com/read-76439.html

最新回复(0)