zoukankan      html  css  js  c++  java
  • 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;
    	}
    };
    
  • 相关阅读:
    《精通CSS网页布局》读书报告 ----2016-12-5补充
    定位始终居中显示
    IntelliJ idea的使用
    模拟发送http请求
    知识漏洞
    【NX二次开发】Block UI 半径尺寸(沿曲线的位置)
    【NX二次开发】Block UI 角度尺寸
    【NX二次开发】Block UI 线性尺寸
    【NX二次开发】Block UI 表达式
    【NX二次开发】Block UI 整形
  • 原文地址:https://www.cnblogs.com/zzw1024/p/12334066.html
Copyright © 2011-2022 走看看