A Java solution


  • 0
    P
    class Solution {
        public String countAndSay(int n) {
            if (n == 1) {
    			return "1";
    		}
    		int count = 1;
    		String startingTerm = "1";
    		int termCount = 1;
    		StringBuilder sbuilder = null;
    		boolean checkSameTerm = false;
    		List<String> list = new ArrayList<>();
    		list.add("1");
    		while (true) {
    			if (count == n) {
    				break;
    			}
    			sbuilder = new StringBuilder();
    			char[] chars = startingTerm.toCharArray();
    			if (count == 1) {
    				sbuilder.append(chars.length).append(startingTerm);
    				list.add(sbuilder.toString());
    				startingTerm = sbuilder.toString();
    				count++;
    				continue;
    			}
    			for (int i = 0; i < chars.length; i++) {
    				if (i + 1 != chars.length && chars[i] == chars[i + 1]) {
    					checkSameTerm = true;
    					termCount++;
    				} else {
    					if (checkSameTerm) {
    						sbuilder.append(termCount).append(chars[i]);
    						checkSameTerm = false;
    						termCount = 1;
    					} else {
    						sbuilder.append(1).append(chars[i]);
    					}
    				}
    			}
    			startingTerm = sbuilder.toString();
    			list.add(sbuilder.toString());
    			termCount = 1;
    			count++;
    		}
    		
    		return list.get(n-1);
        }
    }
    

Log in to reply
 

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