LeetCode 6. ZigZag Conversion 解题报告

来源:互联网 发布:php.ini设置文件大小 编辑:程序博客网 时间:2024/06/06 09:05

题目描述:

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


解题思路:

  本题题意为以z字形格式排列的字符串逐行读出来。由于行数不确定,所以使用vector相对于数组来说更方便一些。使用一个bool变量odd来标记此时字符向下排列(如)还是斜向上方排列。

P   A   H   NA P L S I I GY   I   R              p->A->Y即为odd为真时向下排列 
 向下排列

P   A   H   NA P L S I I GY   I   R              Y->P->A为斜向上排列。但是此时Y和A分别被包含在前两个向下的排列中。P则在odd为假时被加入第二行。
斜向上排列




代码展示

#include <iostream>#include <string>#include <vector>class Solution {public:    string convert(string s, int numRows) {        vector<char> tmp;        vector<vector<char> > res;        for(int i=0 ; i<numRows ; i++)        {            res.push_back(tmp);        }        bool flag =false;        //int jj =0;        bool odd = true;//odd 标记序列向下移动        for(int i=0 ; i<s.size()&&!flag;)        {            if(odd)            {                for(int j=0; j<numRows ;j++)                {                    res[j].push_back(s[i]);                    i++;                    if(i==s.size())                    {                        flag = true;                        break;                    }                                }                odd = !odd;            }            else            {                for(int j=numRows-2; j>0 ;j--)                {                    res[j].push_back(s[i]);                    i++;                    if(i==s.size())                    {                        flag = true;                        break;                    }                                }                odd = !odd;            }                    }        string ans;        for(int i=0;i<res.size();i++)        {            for(int j=0 ; j<res[i].size();j++)                ans+=res[i][j];        }        return ans;}};


0 0
原创粉丝点击