LeetCode solution in Java