【leetcode】ZigZag——easy

zigzag型输出字符串。

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

思路:其实就是生成一个row*s.length()大小的二维数组,然后以w型方式去存储每一个字符,横向输出就行了。

#include <iostream>
#include<string>
using namespace std;

class Solution {
public:
    string convert(string s, int numRows) {
        string s_convert;
        int numCols=s.size();
         //二维char型数组的内存分配和初始化
        char** c_array;
        c_array=(char**)malloc(numRows*sizeof(char*));    
        for(int k=0;k<numRows;k++)
        {
            c_array[k]=(char*)malloc(numCols*sizeof(char));
        }
        for(int m=0;m<numRows;m++)
            for(int n=0;n<numCols;n++)
                c_array[m][n]='0';
        //往二维数组中存入数据
        int i=0,j=0;
        int i_add=-1;
        while(j<numCols) 
        {
            c_array[i][j]=s[j];
            if(numRows==1)
                j++;
            else
            {
                if(i==numRows-1||i==0)         //每次到达顶端或者底端时,i的增量取反
                    i_add=-i_add;
                i+=i_add;
                j+=1;
            }
        }
        //取出数据
        for(i=0;i<numRows;i++)
        {
            for(j=0;j<numCols;j++)
            {
                if(c_array[i][j]!='0')
                    s_convert+=c_array[i][j];
            }
            free(c_array[i]);
        }
        free(c_array);
        return s_convert;
    }
};

void main()
{
    string s="ab";
    Solution S;
    cout<<S.convert(s,1);
}

 

你可能感兴趣的:(LeetCode)