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;
        }
    };
  • 相关阅读:
    正则表达式
    浏览器 User-Agent 大全
    python3爬虫开发实战 第六课 爬虫基本流程
    python3爬虫开发实战 第五课 常用库的安装
    python3爬虫开发实战 第四课 MySQL
    python3爬虫开发实战 第三课 Redis数据库
    python3爬虫开发实战 第二课 MongoDB安装
    python3爬虫开发实战 第一课 python安装和Pycharm安装
    批处理——数据库
    Aop所需包
  • 原文地址:https://www.cnblogs.com/igoslly/p/9017638.html
Copyright © 2011-2022 走看看