LeetCode: Count and Say

题意理解有误,看了网上答案才弄出来

 1 class Solution {

 2 public:

 3     string countAndSay(int n) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         string pre = "";

 7         if (n == 0) return pre;

 8         pre = "1";

 9         for (int i = 1; i < n; i++) {

10             string tmp = "";

11             int len = pre.size();

12             int beg = 0;

13             char last = '*';

14             int count = 0;

15             while (beg < len) {

16                 if (pre[beg] == last) 

17                     count++;

18                 else {

19                     if (last != '*') {

20                         tmp += count+'0';

21                         tmp += last;

22                     }

23                     last = pre[beg];

24                     count = 1;

25                 }

26                 beg++;

27             }

28             tmp += count+'0';

29             tmp += last;

30             pre = tmp;

31         }

32         return pre;

33     }

34 };

 

 1 public class Solution {

 2     public string CountAndSay(int n) {

 3         string pre = "";

 4         if (n == 0) return pre;

 5         pre = "1";

 6         for (int i = 1; i < n; i++) {

 7             string tmp = "";

 8             int len = pre.Length;

 9             int beg = 0;

10             char last = '*';

11             int count = 0;

12             while (beg < len) {

13                 if (pre[beg] == last) count++;

14                 else {

15                     if (last != '*') {

16                         tmp += count;

17                         tmp += last;

18                     }

19                     last = pre[beg];

20                     count = 1;

21                 }

22                 beg++;

23             }

24             tmp += count;

25             tmp += last;

26             pre = tmp;

27         }

28         return pre;

29     }

30 }
View Code

 

你可能感兴趣的:(LeetCode)