AC solution in Java


  • 0
    L
    public class Solution {
        public String countAndSay(int n) {
            String ans = "1";
            while (--n > 0) {
                StringBuilder sb = new StringBuilder();
                char[] ansChars = ans.toCharArray();
                for (int i = 0; i < ansChars.length; i++) {
                    int count = 1;
                    while (i + 1 < ansChars.length && ansChars[i] == ansChars[i + 1]) {
                        i++;count++;
                    }
                    sb.append(String.valueOf(count) + String.valueOf(ansChars[i]));
                }
                ans = sb.toString();
            }
            return ans;
        }
    }
    

    This question is rather straightforward once one understands what the question means. Deriving from the example given, one essentially counts identical consecutive characters and put both the count and the character for the next iteration.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.