38. Count and Say

    xiaoxiao2021-03-25  87

    The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ...

    1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211.

    Given an integer n, generate the nth sequence.

    Note: The sequence of integers will be represented as a string.

    百度过才明白题意是什么:题目的意思是输入的整型数n,翻译的第几次序列(例子中的111221对应n=5),

    此外当前次的序列是由上一次再翻译得到的比如(21是1个2和1个1所以再翻译就是1211,而1211是由1个1+1个2+2个1得到再翻译就是111221)

    只要n>=2 那么都是由起始字符串“1”经过n次翻译过来的,每次统计都是从字符序列的首个字母‘1’开始翻译的

    public String countAndSay(int n) { if(n<0) return ""; if(n==1) return "1"; String output="1"; StringBuffer sb=null; for(int i=2;i<=n;i++){//每次报数都是从首字母开始统计 sb=new StringBuffer(); int count=0;//统计重复个数 char c=output.charAt(0);//首个字符 for(int j=0;j<output.length();j++){ if(output.charAt(j)==c){ count++; }else{ sb.append(count); sb.append(c); c=output.charAt(j); count=1; } } sb.append(count); sb.append(c); output=sb.toString(); } return output; }

    转载请注明原文地址: https://ju.6miu.com/read-16448.html

    最新回复(0)