zoukankan      html  css  js  c++  java
  • LeetCode 6

    一、问题描述

    Description:

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

    根据给出的行数,按 “之” 字形排列源字符串,然后一行一行地输出字符串。


    二、解题报告

    本题主要是理解题意,输入一个字符串和一个行数,按“之”字形排列该字符串的字符,如下图:



    这是 3 行的之字形,如果是 4 行的话:



    以此类推。

    思路:根据上面分析的规律,我们只需定义一个字符串数组,大小为行数(即每一行对应一个字符串)。然后遍历输入字符串,将每个字符插入对应行的字符串即可。

    class Solution {
    public:
        string convert(string s, int numRows) {
            if(numRows == 1)
                return s;
    
            vector<string> v(numRows,"");  // 创建numRows个字符串
            int idx = 0;
            bool flag = true;
            for(int i=0; i<s.size(); ++i)
            {
                v[idx] += s[i];
    
                if(flag)
                    ++idx;
                else
                    --idx;
    
                if(idx == numRows-1)
                    flag = false;
                if(idx == 0)
                    flag = true;
            }
    
            // 输出
            string output = "";
            for(int i=0; i<numRows; ++i)
                output += v[i];
            return output;
        }
    };





    LeetCode答案源代码:https://github.com/SongLee24/LeetCode


  • 相关阅读:
    基于PI的Webservice发布实例
    SM30 表格维护生成器
    各种财务凭证的冲销
    SAP后台作业记录操作
    特性,批次特性建立的BAPI函數
    Windows 上 Nginx 路径的陷阱
    BitKeeper 和 Git
    Javascript 正则验证带 + 号的邮箱地址
    FastAdmin 开发第三天:认识目录
    PHP 中的对象传递
  • 原文地址:https://www.cnblogs.com/songlee/p/5738063.html
Copyright © 2011-2022 走看看