• LeetCode——006 ZigZag Conversion


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

    ** Solution: **

    注意输入的字母排序是按照倒着的N排序的,然后让你根据这个倒置的N的图形进行按行排序输出
    按照半个N,即:一个竖和一个行的循环将数据输入到每一行中
    比如输入:0,1,2,3,4,5,6,7,8,9,10;4行
    其形状为
    0 6
    1 5 7
    2 4 8 10
    3 9
    按照半个N,即0,1,2,3 与4,5 为循环,然后确定半个N的大小为size = 2 * numRows - 2 = 6
    半个N的下竖为, 存入行[i%size],上斜存入[size - i % size];

    class Solution {
    public:
    	string convert(string s, int numRows) {
    		if (s.length() < 2 || numRows < 2)return s;
    		string res = "";
    		vector<string>rows(numRows, "");
    		int size = 2 * numRows - 2;//半个N的大小
    		for (int i = 0; i < s.length(); ++i)
    		{
    			int id = i % size;
    			if (id < numRows)//竖下
    				rows[id] += s[i];
    			else//斜上
    				rows[size - id] += s[i];
    		}
    		for (auto str : rows)
    			res += str;
    		return res;
    	}
    };
    
  • 相关阅读:
    四则运算(判断正误)
    Right-BICEP要求四则2的测试用例
    《构建之法》阅读笔记02
    第二周的学习进度
    四则运算(升级)
    构建之法阅读笔记01
    新手安装使用codeblocks
    新的一年你该如何起飞
    中国国家图书馆 注册后可以免费使用 维普等多个数据库资源
    c++学籍管理系统v1.10
  • 原文地址:https://www.cnblogs.com/zzw1024/p/12334066.html
Copyright © 2020-2023  润新知