zoukankan      html  css  js  c++  java
  • Leetcode0006--ZigZag Conversion

    【转载请注明】https://www.cnblogs.com/igoslly/p/9017638.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;
        }
    };
  • 相关阅读:
    973. K Closest Points to Origin
    919. Complete Binary Tree Inserter
    993. Cousins in Binary Tree
    20. Valid Parentheses
    141. Linked List Cycle
    912. Sort an Array
    各种排序方法总结
    509. Fibonacci Number
    374. Guess Number Higher or Lower
    238. Product of Array Except Self java solutions
  • 原文地址:https://www.cnblogs.com/igoslly/p/9017638.html
Copyright © 2011-2022 走看看