leetcode之ZigZag Conversion

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   N
A P L S I I G
Y   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‘ 字型排列(感觉说 N 更形象。。),然后从左到右,从上到下进行输出

思路:我的思路就是用一个二维数组将他们都存储保存到数组里,写的较为复杂,但能通过,我看了下别人的,可以只创建一个一维的string类型数组,然后将每个字符存储到相应的数组中;

这是二维数组较复杂的代码:

class Solution {
public:
    string convert(string s, int n) {
        if(n==1)return s;
        int len = s.size();
        vector<vector<char> >vec(n,vector<char>(len));
        for(int i=0;i<n;i++){
            for(int j=0;j<len;j++){
                vec[i][j]='0';
            }
        }
        int i,j=0,k=0;
        bool f=true;
        for(i=0;i<len;i++){
            vec[j][k]=s[i];
            if(f){
                if(j==n-1){
                    f=false;
                    j--,k++;
                    continue;
                }
                j++;
            }
            else{
                if(j==0){
                    f=true;
                    j++;
                    continue;
                }
                k++;j--;
            }
        }
        string res="";
        for(int i=0;i<n;i++){
            for(int j=0;j<len;j++){
                if(vec[i][j]!='0')
                    res+=vec[i][j];
            }
        }
        return res;
    }
};

这是一维的string类数组的解法:

class Solution {
public:
    string convert(string s, int n) {
        if(n<=1)return s;

        int k=0,step=1;
        string* str=new string[n];
        
        for(int i=0;i<s.size();i++){
            str[k]+=s[i];
            
            if(k==0)step=1;
            if(k==n-1)step=-1;
            
            k+=step;
        }
        string res="";
        for(int i=0;i<n;i++)
            res+=str[i];
        return res;
    } 
};

猜你喜欢

转载自blog.csdn.net/godop/article/details/79911996