• 力扣(LeetCode)试题6-Z字形变换 C++代码


    这周课题组比较忙,牺牲了练题时间,该打该打。。。

    中等题型,对于我还是挺难的 ಥ﹏ಥ ,不得不从答案找思路,这道题对于我的难点在于一次性生成numRows个容器/字符串

    对于vector<>数据类型不是很熟悉,只好进行了遍历、拼接等操作,遍历了好几次,时间复杂度估计有点高,之后熟悉vector操作后再来改进。第一版代码如下:

     1 #include <iostream>
     2 #include <vector>
     3 #include <algorithm>
     4 
     5 using namespace std;
     6 
     7 class Solution 
     8 {
     9 public:
    10     string convert(string s, int numRows) 
    11     {
    12         if (numRows == 0) return "数据不合法";
    13         {
    14             if (numRows == 1 || s == "") return s;
    15             else
    16             {
    17                 int rows = min(numRows, int(s.size()));
    18                 //一次生成rows个string类型的容器
    19                 vector<string> str(rows);
    20                 string result = "";
    21                 int flag = -1;//控制步长的方向,+1还是-1
    22                 int count = 0;//分配器,若为0或者rows-1,则反向
    23 
    24                 for (int i = 0; i < s.length(); i++)
    25                 {
    26                     if (count == 0 || count == rows - 1)
    27                     {
    28                         flag = -flag;
    29                     }
    30                     str[count].push_back(s[i]);//将第i个值存入str[count]容器中
    31                     count += flag;
    32                 }
    33 
    34                 int j = 1;//指向str[j]容器,依次取出字符,并拼接
    35                 while (j < rows)
    36                 {
    37                     for (int k = 0; k < str[j].size(); k++)
    38                     {
    39                         str[0].push_back(str[j][k]);
    40                     }
    41                     j += 1;
    42                 }
    43 
    44 
    45                 for (int q = 0; q < str[0].size(); q++)
    46                 {
    47                     result += str[0][q];
    48                 }
    49                 return result;
    50             }
    51         }
    52     }
    53 };
    54 
    55 int main()
    56 {
    57     Solution sol;
    58     string s = "";
    59     int n = 0;
    60     string result;
    61     result = sol.convert(s, n);
    62     for (int i = 0; i < result.size(); i++)
    63         cout << result[i];
    64 
    65     cout << endl;
    66 
    67     int u;
    68     cin >> u;
    69 
    70     return 0;
    71 }

  • 相关阅读:
    7.6实战练习
    构造方法的主要应用
    6.0字符串String
    数组冒泡排序
    数组(二维数组)
    5.1数组(一维部分)
    4个方位的三角形和菱形
    4.3循环语句
    控制台输入输出
    4 java语句 4.2条件语句
  • 原文地址:https://www.cnblogs.com/pgzhanglin/p/13347162.html
Copyright © 2020-2023  润新知