• A1140 Look-and-say Sequence(20分)PAT 甲级(Advanced Level) Practice(C++)满分题解【字符串处理】


    Look-and-say sequence is a sequence of integers as the following:

    D, D1, D111, D113, D11231, D112213111, ...
    

    where D is in [0, 9] except 1. The (n+1)st number is a kind of description of the nth number. For example, the 2nd number means that there is one D in the 1st number, and hence it is D1; the 2nd number consists of one D (corresponding to D1) and one 1 (corresponding to 11), therefore the 3rd number is D111; or since the 4th number is D113, it consists of one D, two 1's, and one 3, so the next number must be D11231. This definition works for D = 1 as well. Now you are supposed to calculate the Nth number in a look-and-say sequence of a given digit D.

    Input Specification:

    Each input file contains one test case, which gives D (in [0, 9]) and a positive integer N (≤ 40), separated by a space.

    Output Specification:

    Print in a line the Nth number in a look-and-say sequence of D.

    Sample Input:

    1 8
    

    Sample Output:

    1123123111

    题意分析:

    先找规律,新的字串计算前一个字串中出现的数字个数,注意不是按所有数字数来算,相同的数字不连续断开后要重新计算,一开始一直算的整个字符串中的数字数,手算结果一直不对,要注意

    代码如下:

    我的AC代码: 

    1. #include
    2. using namespace std;
    3. //D, D1, D111, D113, D11231, D112213111, ...
    4. int main()
    5. {
    6. string s;
    7. int n;
    8. cin >> s >> n;
    9. if (n == 1) {
    10. cout << s << endl;
    11. return 0;
    12. }
    13. s += "1";
    14. for (int i = 2; i < n; i++) {
    15. string t = s;
    16. s = t[0];
    17. bool continuous = false;
    18. int cnt=1;
    19. for (int j = 1; j < t.length(); j++) {
    20. if (t[j] == t[j - 1]) {
    21. continuous = true;
    22. cnt++;
    23. }
    24. else continuous = false;
    25. if (!continuous) {
    26. s += to_string(cnt);
    27. s += t[j];
    28. cnt = 1;
    29. }
    30. }
    31. s += to_string(cnt);
    32. }
    33. cout << s << endl;
    34. return 0;
    35. }

     *柳神的更简洁,但要仔细看:

    1. #include
    2. using namespace std;
    3. int main() {
    4. string s;
    5. int n, j;
    6. cin >> s >> n;
    7. for (int cnt = 1; cnt < n; cnt++) {
    8. string t;
    9. for (int i = 0; i < s.length(); i = j) {
    10. for (j = i; j < s.length() && s[j] == s[i]; j++);
    11. t += s[i] + to_string(j - i);
    12. }
    13. s = t;
    14. }
    15. cout << s;
    16. return 0;
    17. }

    运行结果如下:

     

  • 相关阅读:
    重大发现,AQS加锁机制竟然跟Synchronized有惊人的相似
    [Qt]基础数据类型和信号槽
    支撑向量机
    tensorboard attempted to bind to port 6006,but it was already in use
    智能温室大棚监控 环境监控 视频监控网关数采仪应用
    极轨气象卫星数据中的蝴蝶结(BOW-TIE)处理
    Vue 监听路由及权限设置
    一遍掌握,快速排序的入门理解
    一文搞懂RepVGG网络
    跨越单线程限制:Thread类的魅力,引领你进入Java并发编程的新纪元
  • 原文地址:https://blog.csdn.net/qq_47677800/article/details/126181432