Solve #34 in scala