Count and Say
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"
or11
.
11
is read off as"two 1s"
or21
.
21
is read off as"one 2
, thenone 1"
or1211
.Given an integer n, generate the *n*th 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"
public String countAndSay(int n) { if(n<1) return null; String result="1"; for(int i=2;i<=n;i++){ result=countAndSay(result); } return result ; } public String countAndSay(String str) { //获取下一个字符串 StringBuilder builder=new StringBuilder(); //构建一个空的字符串构造器; int count=1; for(int i=1;i<str.length();i++){ if(str.charAt(i)==str.charAt(i-1)) count++; else{ builder.append(count); builder.append(str.charAt(i-1)); count=1; } } builder.append(count); builder.append(str.charAt(str.length()-1)); return builder.toString(); } //主要学习了StringBuider的用法;Java可以使用+好连接字符串,但每次连接字符串时会构建一个新的String对象,既耗时,又浪费空间,使用StringBuffer类可以避免此类问题;调用append()方法向其中增加内容; StringBuider和StringBuffer的区别: (1)两个类的API相同; (2)StringBuider在单线程中使用 (3)StringBuffer允许使用多线程方式增加和删除字符,但效率比StringBuider较低。
Count and Say
最新推荐文章于 2021-10-15 01:07:30 发布