Leetcode0006--ZigZag Conversion

【转载请注明】http://www.cnblogs.com/igoslly/p/8726771.html

 

来看一下题目:

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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

题目意思:

   给出字符串和行数

   设计出一种“竖-斜”式的显示形式

   结果给出按横行读取的数值

下面的图可能能更好的解释图示法:

总的来说:

1、显示法

      利用代码实现zigzag这样的变形,再按读取方向输出

     

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows==1){return s;}
        int length = s.size(),count=0;
        char zigzag[numRows][length];       // 设定行、列矩阵
        fill(zigzag[0],zigzag[0]+numRows*length,'#');    // 初始化二维数组,首位置为zigzag[0]
        enum{down,linear};                  //  设定方向
        int dir=down,x=0,y=0;
        while(count<s.size()){
            switch(dir){                // 判断方向
                case down:
                    zigzag[x++][y]=s[count++];
                    //  当竖行越界后,已经到达末行+1,需要进行位置调整x-2,y+1
                    if(x>=numRows){dir=linear;x-=2;y++;}    
                    break;
                case linear:
                    zigzag[x--][y++]=s[count++];
                    //  当斜行越界后,到达首行-1,需要进行位置调整x+2,y-1
                    if(x<0){dir=down;x+=2;y--;}
                    break;
            }
        }
        string result;
        for(int i=0;i<numRows;i++){
            for(int j=0;j<length;j++){
                if(zigzag[i][j]!='#'){
                    result+=zigzag[i][j];
                }
            }
        }
        return result;
    }
};

2、中心扩展法

    对于回文串,从对称轴展开的字符均相同;把字符串的每个位置作为回文串的对称轴,判断回文串的最大长度;子串对称轴遍历复杂度为O(n),回文判断O(n)

    这里要注意:长度为奇数 / 偶数时,对称轴的位置不同

猜你喜欢

转载自www.cnblogs.com/igoslly/p/9017638.html