You can make it look simpler as well:
https://discuss.leetcode.com/topic/103329/java-solution