06Z字形变换

leetcode06 [Z字形变换]

题目描述

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

Example: 输入字符串为 "LEETCODEISHIRING" 行数为 "3" 时,排列如下:
return :
L   C   I   R
E T O E S I I G
E   D   H   N

solution idea

按行排序

通过从左向右迭代字符串,我们可以轻松地确定字符位于 Z 字形图案中的哪一行

class Solution {
public:
    string convert(string s, int numRows) {

        if (numRows==1) return s;

        vector<string> rows(min(numRows, int(s.size())));
        int cur_row=0;
        bool up_or_down=false;

        for (char c : s)
        {
            rows[cur_row]+=c;
            if (cur_row == 0 || cur_row == numRows - 1) up_or_down = !up_or_down;
            cur_row+=up_or_down ? 1 : -1;
        }
        string str_convert;
        for (string row : rows)
        {
            str_convert+=row;
        }
        return str_convert;
    }
};
c++ 语法
STL-string 基本操作

string 表示可变长的字符序列,必须包含string头文件(#include)

初始化和定义对象

string s1 //默认初始化,s1是一个空字符串

string s2=‘hello’ //

string s3=(10,‘a’) // s3=‘aaaaaaaaaa’
在这里插入图片描述

string 操作

在这里插入图片描述

cctype 头文件函数

在这里插入图片描述

Additional Tricks:

STL对象的遍历

for (char c : s)//对 string对象s进行遍历
{
    rows[cur_row]+=c;
}
<=>
for (int i=0;i<s.size();i++)
{
    rows[cur_row]+=s[i];
}

for (string row : rows)//对 vector 对象rows 遍历
{
    str_convert+=row;
}

添加字符

+=,append(),push_back()
rows[cur_row]+=c;
str_convert+=row;

参考文献

  1. c++ prime 第5版
  2. c++ 标准库
  3. devdocs
  4. leetCode—Z 字形变换、for、string、vector笔记
  5. leetCode—Z 字形变换、for、string、vector笔记
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值