Just run
javac Main.java
Then
java Main < input.txt
To see the algorithm working.
That just reads character by character entries from input.txt or the CLI on your system using BufferedReader class instead Scanner.
The BufferedReader implementation is most performatic.