LeetCode 38 Count and Say(字符串规律输出)
2017-03-11 14:41
375 查看
题目链接:https://leetcode.com/problems/count-and-say/?tab=Description
1—>11—>21—>1211—>111221—>312211—>….
按照上面的规律进行求解出第n个字符串是什么。
规律:相连的数字有多少个然后添加上这个数字
参考代码:
1—>11—>21—>1211—>111221—>312211—>….
按照上面的规律进行求解出第n个字符串是什么。
规律:相连的数字有多少个然后添加上这个数字
参考代码:
package leetcode_50; /*** * * @author pengfei_zheng * 按照规律进行求解字符串 */ public class Solution38 { public static String countAndSay(int n) { if(n<=0) { return ""; } String s="1"; int times = 1; while(times<n){ s = getSay(s); times++; } return s; } private static String getSay(String s) { int count =0; StringBuilder str = new StringBuilder(""); for(int i = 0; i<s.length(); i++){ //first to add in order to prevent thinking about the index count ++; //not reach the end of s and next item is not equal to the pre item if ((i< s.length()-1) && (s.charAt(i) != s.charAt(i + 1))) { str = str.append(count).append(s.charAt(i));//rebuild the str count = 0;//reset count to zero } else if ((i == s.length()-1)) {//meet the end of s str = str.append(count).append(s.charAt(i)); } } return str.toString(); } public static void main(String[]args){ String s = countAndSay(2); System.out.println(s); } }
相关文章推荐
- 【LeetCode 38_字符串_算术运算】Count and Say
- LeetCode 38 Count and Say(字符串生成)
- [LeetCode]38 Count and Say
- [Leetcode 38, Easy] Count and Say
- LeetCode(38) Count and Say
- leetcode_question_38 Count and Say
- [LeetCode] Count and Say 字符串
- Leetcode 38 Count and Say
- leetcode[38]:Count and Say
- LeetCode_38---Count and Say
- LeetCode(38) Count and Say
- leetcode[38]Count and Say
- leetcode-38 count and say
- [leetcode-38]count and say(java)
- LeetCode | Count and Say(统计并输出)
- LeetCode38——Count and Say
- LeetCode 38 Count and Say
- leetcode-38 Count and Say
- 【LeetCode】38 - Count and Say
- LeetCode(38)题解: Count and Say