Java iterative solution beats 73%...


  • 0
    public class Solution {
        public String countAndSay(int n) {
            if (n == 0) {
                return "";
            }
            if (n == 1) {
                return "1";
            }
            int i = 1;
            String s = "1";
            StringBuilder sb;
            char[] arr;
            int step = 0, skip = 0;
            while (i != n) {
                sb = new StringBuilder();
                i += 1;
                step = 0;
                skip = 0;
                arr = s.toCharArray();
                while (step < arr.length) {
                    if (arr[step] != arr[skip]) {
                        int num = step - skip;
                        sb.append(num);
                        sb.append(arr[skip]);
                        skip = step;
                    }
                    step += 1;
                }
                sb.append(step - skip);
                sb.append(arr[step - 1]);
                s = sb.toString();
            }
            return s;
        }
    }
    

Log in to reply
 

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