leetcode Count and say

来源:互联网 发布:淘宝下载器 编辑:程序博客网 时间:2024/05/10 08:22


38. Count and Say

My Submissions
Total Accepted: 77548 Total Submissions: 269947 Difficulty: Easy

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.

Subscribe to see which companies asked this question


public class Solution {    public String countAndSay(int n) {        String ans="1";        for(int i = 1; i < n; i++){            ans = read(ans);        }        return ans;    }
    public String read(String s){        int len = s.length();        StringBuilder builder = new StringBuilder(128);        char pri = s.charAt(0),now;        int count = 1;        for(int i = 1; i < len;i++){            now = s.charAt(i);            if(pri == now){                count++;            }            else{                builder.append(count);                builder.append(pri);                pri = now;                count = 1;            }        }        builder.append(count);        builder.append(s.charAt(len-1));        return builder.toString();    }}

//stringbuilder 还要学习下


0 0