Clean and simple java solution beats 84%


  • 2
    D
    public String countAndSay(int n) {
    	String str = "1";
    	for (int i = 1; i < n; i++)
    		str = count(str);
    	return str;
    }
    
    private String count(String s) {
    	StringBuilder sb = new StringBuilder();
    	int n = 0, i = 0, j = 0;
    	while (i < s.length()) {
    		char ch = s.charAt(i);
    		while (j < s.length() && ch == s.charAt(j))
    			j++;
    		n = j - i;
    		sb.append(n).append(ch - '0');
    		i = j;
    	}
    	return sb.toString();
    }
    

    111221 for examp:

    1. i=0 ,ch='1',j=0..1..2..3,there are n=j-i=three 1,i=j=3;"31"
    2. i=3,ch='2',j=3..4..5,there are n=j-i=two 2,i=j=5;"3122"
    3. i=5 ch='1',j=5.6,there are n=j-i=one 1,i=j=6;"312211"-return

  • 0
    F
    public String next(String s) {
            char[] chars = s.toCharArray();
            int i = 0;
            int count = 1;
            StringBuilder sb = new StringBuilder();
            for (int j = 1; j < chars.length; j++, count++) {
                if (chars[j] != chars[i]) {
                    sb.append(count).append(chars[i] - '0');
                    i = j;
                    count = 0;
                }
            }
            sb.append(count).append(chars[i] - '0');
            return sb.toString();
        }
    
        public String countAndSay(int n) {
            String s = "1";
            while (--n > 0) {
                s = next(s);
            }
            return s;
        }
    

    The same way, but I use for loop instead of while loop.


Log in to reply
 

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