Count and Say
题目地址:
https://leetcode.com/problems/count-and-say/#/description
题目:
解题思路:
这道题主要运用bfs的思想。这里有三个循环,要弄清每个循环的作用。
代码:
https://leetcode.com/problems/count-and-say/#/description
题目:
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.
解题思路:
这道题主要运用bfs的思想。这里有三个循环,要弄清每个循环的作用。
代码:
public String countAndSay(int n) { String old = "1"; while(n > 1){ StringBuilder sb = new StringBuilder(); // this is start of one level for(int i = 0; i <= old.length() - 1; i++){ char curr = old.charAt(i); int count = 1; while(i + 1 <= old.length() - 1 && curr == old.charAt(i + 1)){ count++; i++; } sb.append(count).append(curr); } old = sb.toString(); n--; } return old; }

Comments
Post a Comment