[LeetCode] [C++] 6. 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 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".
LeetCode 6在线测试

问题描述

第一眼看到这个题目一脸懵逼,什么意思??? 后台百度了下才明白题目意思。就是给定一个字符串
以及int型整数(这个整数用于控制输出几行),以"之"字形的方式输出N行,最后横向来看原来的字符串。
例如:给定字符串"012345678910111213114...",以及输出行数N=5,则之字形输出后的字符串为
之字形输出后样式

思路分析

字符串之字形排序。找出排序规律:一共有N行,则total = 2*(N-1)个字符组成一个完整序列。序列中下标idx % total
如果大于N则下标换为(total-idx) % total ,下标对应在第几行。

例如上文例子中,N=5,则一个序列总共有2*(5-1)=8个数字,从0~4分别处于不同的四行,5~7向上排序。

代码验证
class Solution {
public:
    string convert(string s, int numRows) {
        vector<string> vecStrings;
        
        for (int i = 0; i < numRows; ++i) {
            vecStrings.push_back("");
        }
        
        if (numRows == 1) {
            return s;
        }
        
        int total = 2*(numRows-1);
        for (int i = 0; i < s.size(); ++i) {
            int idx = i % total;
            if (idx > numRows-1) {
                idx = total - idx;
            }
            vecStrings[idx] += s[i];
        }
        
        string ret;
        for (int i = 0; i < numRows; ++i) {
            ret += vecStrings[i];
        }
        
        return ret;
    }
};
总结注意

之字形转换中,注意每一个字符变换后处于的行数row,也就是idx的计算方式。

原创声明

作者:hgli_00
链接:http://www.cnblogs.com/lihuagang/p/leetcode_6.html
来源:博客园
著作权归作者所有,转载请联系作者获得授权。

转载于:https://www.cnblogs.com/lihuagang/p/leetcode_6.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值