Count and Say

来源:互联网 发布:云打包app平台源码 编辑:程序博客网 时间:2024/05/13 22:52

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=1: ans = 1;

n=2: 读n=1的ans,即一个1,ans = 11;

n=3: 读n=2的ans,即两个1,ans = 21;

package leetcode;


public class CountandSay {

public String countAndSay(intn) {

        String ans = "1";

        int j = 1;

        if (n == 1)return "1";

        if (n >1){

        while (j<n){

            ans = revolution(ans);

            j++;

            }

        }

        return ans;

    }

private String revolution(StringfrontStr) {

// TODO Auto-generated method stub

String ans = "";

int count = 1;

if (frontStr.length() == 1) {

ans =ans + count + frontStr;

returnans;

}

char[] chars = frontStr.toCharArray();

charfrontChar = chars[0];

for (inti = 1; i<chars.length;i++){

if (frontChar ==chars[i]){

count++;

}else{

ans =ans + count + frontChar;

count = 1;

frontChar =chars[i];

}

}

ans =ans + count + frontChar;

returnans;

}

public staticvoid main(String[] args) {

// TODO Auto-generated method stub

System.out.println(new CountandSay().countAndSay(6));

}


}


0 0
原创粉丝点击