解决Count and Say

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuxw1/article/details/78987248

一、题目:

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"

Example 2:

Input: 4
Output: "1211"
二、翻译:
1被读为“一个1”或“11”。
11被读为“2”或21。
21被读为“一个2,一个1”或1211。
给定一个整数n,生成计数的n个项并表示序列。


注意:整数序列中的每个术语都将表示为字符串。
三、思路:
	本题目可以这样来理解,如果输入1,那么就是一个1;输入2的话,那么就是“11”,要注意第一个字符1和第二个字符1就一样,这个时候输出“21”;输入3的话,就是“21”,要注意第一个字符2和第二个字符1不一样,这个时候要先考虑第一个字符2,就先拼接1个2,然后拼接1个1,之后输出即可;照上述的说法可以总结出下边的规律,如果字符str[i]和str[i+1]一样,那么就输出n个s[i],如果不一样,就先拼接1个s[i],然后拼接n个s[i],之后输出即可
四、JAVA代码:
 
 
class Solution {
    public String countAndSay(int n) {
	//判断n的值是否合理
        if(n<=0) return "";
		//初始化字符串str
        String str = "1";
        
        while(--n>0){
            StringBuilder sb = new StringBuilder();
			//初始化计数器count
            int count = 0;
            char ch = str.charAt(0);
            for(int i = 0,len = str.length();i<len;i++){
			//如果str[i]和str[i+1]相等,计数器加1,如果不等,则对第一个字符统计并且存到StringBuilder里边去
                if(ch==str.charAt(i)){
                    count++;
                }else{
                    sb.append(count).append(ch);
                    ch=str.charAt(i);
                    count=1;
                }
            }
			//对于相等的情况,将统计后的字符存到stringBuilder里边去,对于不等的情况,将剩下的字符串存到StringBuilder里边去
            sb.append(count).append(ch);
			//转换成字符串形式
            str = sb.toString();
        }
		//经过处理后,返回字符串str
        return str;
    }

}


猜你喜欢

转载自blog.csdn.net/liuxw1/article/details/78987248