leetcode 38. Count and Say

来源:互联网 发布:社交媒体网络安全问题 编辑:程序博客网 时间:2024/06/05 03:36

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.

理解题意:
首先 如果把每一位取出来看的话 就是看这一位和下一位一不一样 一样就计算器加一 不一样就计数器清零
所以只用两个变量 一个count 一个value应该就够了

112131:                   value:1    count:111:                   value:1    count:2    112:                  value:2    count:1    输出211121:                 value:1    count:1    输出2111213:                value:3    count:1    输出11                                                                                                                    输出13
public String countAndSay(int n) {        String[] strings = new String[n];        for(int i = 0;i < n;i++){            if(i == 0) strings[i] = "1";            else strings[i] = countAndSayForString(strings[i-1]);        }        return strings[n-1];    }    public String countAndSayForString(String s) {        StringBuffer result = new StringBuffer();        int count = 0;        char value = ' ';        for(char c:s.toCharArray()){            if(c != value){                if(value != ' '){                    result.append(count + "" + value);                }                 value = c;                count = 1;            }            else {                count ++;            }        }        result.append(count + "" + value);        return result.toString();    }

这道题虽然简单 但是刚开始的时候题意理解错了
n=1 返回1
n=2 返回11
n=3 返回21
n=4 返回1211
n=5 返回111221
这才是题目要的String countAndSay(int n) 函数
之前理解成是 n=5 返回15了 看懂题目很重要!!!

0 0
原创粉丝点击