[LeetCode] 6. ZigZag Conversion (Medium)

原题链接

把字符串按照 ↓↗↓……的顺序,排列成一个 Z 形,返回 从左到右,按行读得的字符串。
思路:
建立一个二维数组来按行保存字符串。
按照 ↓↗↓……的方向进行对每一行加入字符。

太慢了这个解法,Runtime: 96 ms, faster than 3.61% of C++。

class Solution
{
public:
  string convert(string s, int numRows)
  {
    if (numRows <= 1)
      return s;
    string res;
    string zigZag[numRows];
    int len = s.length();
    int dirc = 1; // 1表示方向向下,-1表示方向向上
    int index = 0;
    for (int i = 0; i < len; i++)
    {
      zigZag[index] += s[i];
      if (index == numRows - 1)
        dirc = -1;

      if (index == 0)
        dirc = 1;
      index += dirc;
    }
    for (int i = 0; i < numRows; i++)
    {
      cout << zigZag[i] << endl;
      res += zigZag[i];
    }

    return res;
  }
};

猜你喜欢

转载自www.cnblogs.com/ruoh3kou/p/9906833.html