Leetcode-count-and-say

来源:互联网 发布:mac qq代理服务器 编辑:程序博客网 时间:2024/06/07 16:24

题目描述

 

Thecount-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1is readoff as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.

Given an integer n, generate the nth sequence.

Note: Thesequence of integers will be represented as a string.

其实题目很简单的,理解起来也不难,主要是下标的操作繁琐,我自己试了两个方法,都是下标出错,最后参考别人的代码,真的觉得自己思路还是不够清晰。这一题我要背诵下来!

public class Solution {    public String countAndSay(int n) {           String[] data = new String[n];                 data[0] =  "1";                 for(int i=1; i<n; i++){                 String pre = data[i-1];                 String res = "";                 for(int j=0; j<pre.length() ; ){                         int t = j;                         while(j < pre.length() &&  pre.charAt(j) == pre.charAt(t))                         {                              j++;                         }                              res += String.valueOf(j-t)+pre.charAt(t);                  }                   data[i]= res;                 }        return data[n-1];    }}

0 0
原创粉丝点击