week4-leetcode #6-ZigZag Conversion[Medium]

来源:互联网 发布:hl系统线切割怎么编程 编辑:程序博客网 时间:2024/06/06 19:51

week4-leetcode #6-ZigZag Conversion[Medium]

题目链接:https://leetcode.com/problems/zigzag-conversion/description/

Question

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   NA P L S I I GY   I   R

And then read line by line:

"PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)

should return

"PAHNAPLSIIGYIR"

Solution1[base]

time complecity: O(nm)

space complecity:O(nm)

其中m代表字符串s的长度,n代表行的大小

runtime:85ms

class Solution {public:    string convert(string s, int numRows) {      if (numRows == 1) return s;      int numCols = s.length();      char** myMatrix = initMatrix(numRows, numCols);      myMatrix = fillInMatrix(myMatrix, numRows, numCols, s);      string out = readMatrix(myMatrix, numRows, numCols);      for (int i = 0; i < numRows; i++) {        delete myMatrix[i];      }      delete myMatrix;      return out;    }    char** initMatrix(int numRows, int numCols) {      char** myMatrix = new char*[numRows];      for (int i = 0; i < numRows; i++) {        myMatrix[i] = new char[numCols]();      }      for (int i = 0 ; i < numRows; i++) {        for (int j = 0; j < numCols; j++) {          myMatrix[i][j] = ' ';        }      }      return myMatrix;    }    char** fillInMatrix(char** myMatrix, int numRows, int numCols, string s) {      int indexOfS = 0;      int colIndex = 0;      int rowIndex = -1;      int termLength = 2*numRows-2;      int currentLength = 0;      int length = s.length();      while(indexOfS < length) {        if (currentLength < numRows) {          rowIndex++;          myMatrix[rowIndex][colIndex] = s[indexOfS];        } else {          rowIndex--;          colIndex++;          myMatrix[rowIndex][colIndex] = s[indexOfS];        }        currentLength++;        if (currentLength == termLength) {          currentLength = 0;          rowIndex = -1;          colIndex++;        }        // 字符串填满        indexOfS++;        if (indexOfS == length)          break;      }      return myMatrix;    }    string readMatrix(char** myMatrix, int numRows, int numCols) {      string out = "";      for (int row = 0; row < numRows; row++) {        for (int col = 0; col < numCols; col++) {          if (myMatrix[row][col] != ' ') {            out += myMatrix[row][col];          }        }      }      return out;    }};

​ 思路:构建一个二维数组,将字符串按照ZigZag的规则放入该数组,最后按照每行的顺序去读取数组即可。这里比较复杂的是实现ZigZag规则,ZigZag规则是按照一定的顺序来排列字符。

ZigZag规则n = 11 2 3 4 5n = 21 3 5 7 92 4 6 8 10n = 31     5     92  4  6  8  103     7n  = 41      7        132    6 8     12 143  5   9  11    154      10       16