Count and Say

来源:互联网 发布:武汉 人工智能 编辑:程序博客网 时间:2024/06/06 04:33
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.

题目的难度是easy,感觉不相称呢。题目的意思是,起始字符串是"1",

后一个数是count-and-say前一个数。

public class Solution {    public String countAndSay(int n) {        String s="1";for(int i=1;i<n;i++){StringBuffer t=new StringBuffer();int count=1;for(int j=1;j<s.length();j++){if(s.charAt(j)==s.charAt(j-1))count++;else{t.append(count);t.append(s.charAt(j-1));count=1;}}t.append(count);t.append(s.charAt(s.length()-1));s=t.toString();}return s;    }}
在eclipse中没有用StringBuffer,用的String也可以通过,但在leetcode中就是错误。

0 0