Skip to content

Instantly share code, notes, and snippets.

@djvita
Created April 26, 2014 16:55
Show Gist options
  • Save djvita/11325038 to your computer and use it in GitHub Desktop.
Save djvita/11325038 to your computer and use it in GitHub Desktop.
Given a stream of characters, implement a method that will always return the first character that has only appeared once in the stream. For example, say your stream thus far is a,b,c. A call into getFirstUniqueCharacter would return a. After the next character is read, the stream thus far is a,b,c,a. Now a call to getFirstUniqueCharacter will re…
InputStream is = null;
int i;
char c;
try{
// new input stream created
is = new FileInputStream("C://test.txt");
System.out.println("Characters printed:");
// reads till the end of the stream
while((i=is.read())!=-1)
{
// converts integer to character
c=(char)i;
// prints first character that has only appeared once in the stream
System.out.print(getFirstUniqueCharacter(c));
}
}catch(Exception e){
// if any I/O error occurs
e.printStackTrace();
}finally{
// releases system resources associated with this stream
if(is!=null)
is.close();
}
//Write the implementation for getFirstUniqueCharacter
/*implement a method that will always return the first character that has only appeared once in the stream*/
//thinking it over, for example my name its orederd
//so it will first return the first letter then save and compare to the next, even if not called in stream, it will still be counted
// example vitalianovidaurre
//crate a has, and array
//array order, hash freq,
//if key is null, unique, if key exists, its been repeated
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
public char getFirstUniqueCharacter(char c)
{
//HashTable<char, bool> saver = new HashTable<char, bool>();
Map<Character, Integer> counts = new LinkedHashMap<>str.length();
char[] verifier = new char[];
for(char c : str.tCharArray())
{
counts.put(c, counts.containsKey(c) ? counts.get(c) +1 : 1); //if found key, put it in map
}
for(Entry<Character, Integer> entry : counts.entrySet(){ //go through map to see if there are any new values
if(entry.getValue()==1)
{
char key;
key=entry.getKey();
return key;
System.Out.Println("found repeated char {0}", key);
//first element from list is the first non repeated char from string
}
}
System.Out.Println("didnt find any non repeated char");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment