Leetcode || Count and Say

来源:互联网 发布:婚纱摄影网络销售技巧 编辑:程序博客网 时间:2024/05/18 01:01

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.

package pack;class Solution {    public String countAndSay(int n) {        if(n == 0)                 return null;        String result = "1";   //第一个为"1"        for(int i=2; i<=n; i++) { //从第二个开始,每个都以前一个做参数            result = countAndSay(result);        }        return result;    }    public String countAndSay(String str) {        str += "x";  //最后增一个,便于考虑原本最后一位        int repeat_times = 0; //重复次数        String result = "";        for(int i=0; i<str.length()-1; i++) {            if(str.charAt(i+1) == str.charAt(i)) {                repeat_times++;            }             if(str.charAt(i+1)!=str.charAt(i) && repeat_times==0) {                 result = result + "1" + str.charAt(i);            }            if(str.charAt(i+1)!=str.charAt(i) && repeat_times>0) {                result = result + (repeat_times+1) + str.charAt(i);                repeat_times = 0;            }        }        return result;    }}public class Mian {    public static void main(String[] args) {        System.out.println(new Solution().countAndSay(3));    }}
0 0
原创粉丝点击