leetcode 6. ZigZag Conversion

来源:互联网 发布:广西网络发票管理系统 编辑:程序博客网 时间:2024/05/21 06:43

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".


数学方法拆分成row行,然后都按顺序接上

class Solution {public:string convert(string s, int numRows){if (s.length() <= 2 || numRows == 1)return s;else{   vector<string> str(numRows, "");  //字符串数组            for (int i = 0; i < s.size(); i++){int k = i % (2 * numRows - 2);if (k < numRows)str[k] = str[k] + s[i];elsestr[(2 * numRows - 2) - k] = str[(2 * numRows - 2) - k] + s[i];    }            string ret = "";for (int j = 0; j < numRows; j++)ret += str[j];return ret;}}};


原创粉丝点击