ZigZag Conversion

简介: 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 ...

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

这种题主要是连形状都没弄清楚,悲剧。。。

 

发现所有行的重复周期都是 2 * nRows - 2

对于首行和末行之间的行,还会额外重复一次,重复的这一次距离本周期起始字符的距离是 2 * nRows - 2 - 2 * i

C++代码如下:

#include<iostream>
#include<string>
using namespace std;

class Solution {
public:
        string convert(string s, int nRows) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        string result;
        if (nRows < 2) return s;
        for (int i = 0;i < nRows;++i) {
            for (int j = i;j < s.length();j += 2 * (nRows - 1)) {
                result.push_back(s[j]);
                if (i > 0 && i < nRows - 1) {
                    if (j + 2 * (nRows - i - 1) < s.length())
                        result.push_back(s[j + 2 * (nRows - i - 1)]);
                }
            }
        }
        return result;
    }
};

int main()
{
    Solution s;
    string ss="PAYPALISHIRING";
    string sss="0123456789";
    cout<<s.convert(sss,4)<<endl;
}

运行结果:

相关文章
|
5月前
Leetcode 6.ZigZag Conversion
如上所示,这就是26个小写字母表的5行曲折变换。 其中在做这道题的时候把不需要我们构造出这样五行字符,然后拼接。其实你把字母换成1-n的数字,很容易找到每个位置的字母在原字符串中的位置。
23 0
|
5月前
|
存储
【CSAPP】HW1 | 位向量的应用 Application of bit vectors | Adressing and Byte Ordering
【CSAPP】HW1 | 位向量的应用 Application of bit vectors | Adressing and Byte Ordering
15 0
【CSAPP】HW1 | 位向量的应用 Application of bit vectors | Adressing and Byte Ordering
|
存储 算法 测试技术
UVA240 Variable Radix Huffman Encoding
UVA240 Variable Radix Huffman Encoding
UVA240 Variable Radix Huffman Encoding
|
人工智能
UPC-Match Matching(完全背包dp+字符串)
UPC-Match Matching(完全背包dp+字符串)
59 0
|
索引
Leetcode-Medium 6. ZigZag Conversion
Leetcode-Medium 6. ZigZag Conversion
70 0
Leetcode-Medium 6. ZigZag Conversion
HDOJ 1196 Lowest Bit(二进制相关的简单题)
HDOJ 1196 Lowest Bit(二进制相关的简单题)
78 0
LeetCode---Problem6 ZigZag Conversion
ZigZag问题思路。代码整洁并不一定执行速度就好~
762 0
|
机器学习/深度学习 Perl