前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T60-Z字形变换

【leetcode刷题】T60-Z字形变换

作者头像
木又AI帮
修改2019-07-18 10:10:27
3200
修改2019-07-18 10:10:27
举报
文章被收录于专栏:木又AI帮木又AI帮

【题目】

将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:

代码语言:javascript
复制
L   C   I   R
E T O E S I I G
E   D   H   N

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"

示例 1:

代码语言:javascript
复制
输入: s = "LEETCODEISHIRING", numRows = 
输出: "LCIRETOESIIGEDHN"

示例 2:

代码语言:javascript
复制
输入: s = "LEETCODEISHIRING", numRows = 
输出: "LDREOEIIECIHNTSG"
解释:

L     D     R
E   O E   I I
E C   I H   N
T     S     G

【思路】

首先按照题意得到每一行的字符,接着对所有字符进行拼接即可。

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == :
            return s
        res = ""
        ls = ["" for i in range(numRows)]
        count = 
        flag = True
        for si in s:
            ls[count] += si
            # 从上到下
            if flag:
                if count == numRows - :
                    count -= 
                    flag = False
                else:
                    count += 
            # 从下到上
            else:
                if count == :
                    count += 
                    flag = True
                else:
                    count -= 
        # 拼接字符串
        for lsi in ls:
            res += lsi
        return res

C++版本

代码语言:javascript
复制
class Solution {
public:
    string convert(string s, int numRows) {
        vector<string> ls(numRows, "");
        bool direction = true;
        string res="";
        int count=;
        // 特殊情况处理
        if(numRows ==  || s.size() <= numRows)
            return s;
        for(auto si:s){
            ls[count] += si;
            // 从上到下
            if(direction){
                if(count == numRows - ){
                    count--;
                    direction = false;
                }else
                    count++;
            // 从下到上
            }else{
                if(count == ){
                    count++;
                    direction = true;
                }else
                    count--;
            }
        }
        // 拼接字符串
        for(auto lsi: ls)
            res += lsi;
        return res;
    }
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-05-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档