Parsing algorithm in Java