Count and Say(tag:String)

来源:互联网 发布:徕卡ts02plus导出数据 编辑:程序博客网 时间:2024/06/16 17:40

Qustion:

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

1.     12.     113.     214.     12115.     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: 1Output: "1"

Example 2:

Input: 4Output: "1211"

Solution:

    public String countAndSay(int n)     {       StringBuilder str;    StringBuilder res = new StringBuilder("");    int p=0;    char sp;    char sq;        if(n==1)        return "1";        else        {        str=new StringBuilder(countAndSay(n-1));        for(int i=0;i<=str.length();i++)        {        sp=str.charAt(p);        sq=i==str.length()?' ':str.charAt(i);               if(sp!=sq||i==str.length())        {        res.append((i-p)).append(sp);        p=i;        }        }        }        return res.toString();    }

总结:

字符串总变化的时候StringBulider比String效率高。

执行速度:StringBuilder>StringBuffer。

线程安全:StringBuilder不安全,StringBuffer安全。

使用选择:1.如果要操作少量的数据用String;

                    2.单线程操作字符串缓冲区下操作大量数据用StringBuilder;

                    3.多线程操作字符串缓冲区下操作大量数据用StringBuffer。

原创粉丝点击