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

     Solution:

    class Solution {
    public:
        string convert(string s, int nRows) {
            string *tmpS = new string[nRows + 1];
            string ans;
            if(nRows < 2) return s;
            
            bool down = true;
            int row = 0;
            
            for(int i = 0;i < s.length();i++)
            {
                if(row == -1)
                {
                    row = 1;
                    down = true;
                    tmpS[row] += s[i];
                    row++;
                }
                else if(row == nRows)
                {
                    row = nRows - 2;
                    down = false;
                    tmpS[row] += s[i];
                    row--;
                }
                else
                {
                    tmpS[row] += s[i];
                    if(down) row++;
                    else row--;
                }
            }
            
            for(int i = 0;i < nRows;i++)
                ans += tmpS[i];
            return ans;
        }
    };
  • 相关阅读:
    练习5.6.3节
    size_t
    练习3.43
    use include to read a file
    ACM数学(转)
    POJ 2039 To and Fro
    poj 1716 差分约束
    poj 3159 差分约束
    hdu 4571 floyd+动态规划
    poj 1364 差分约束
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3594839.html
Copyright © 2020-2023  润新知