Qustion:
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1 2. 11 3. 21 4. 1211 5. 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: 1 Output: "1"
Example 2:
Input: 4 Output: "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。