栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode算法复健日记:6.Z字形变换

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode算法复健日记:6.Z字形变换

6.Z字形变换

题目描述:将一个给定字符串s根据给定的行数numRows,从上往下、从左到右进行Z字形排列

示例:

输入:s = "PAYPALISHIRING", numRows = 4
输出:"PINALSIGYAHRPI"
解释:
P     I    N
A   L S  I G
Y A   H R
P     I

输入:s = "A", numRows = 1
输出:"A"

思路:

用vectornewStr,字符串数组作为新数组,遍历s,加到对应行的字符串后面。
遍历思路:根据up(路线方向)看current是++还是--,如果current到最上或最下了,up转向

代码+解析:

class Solution {
public:
    string convert(string s, int numRows) {
        int len = s.size();

        if(len == 1 || numRows == 1 || len <= numRows){ //只有1个的情况
            return s;
        }

        vector newStr(numRows);
        int current = 0; //当前行
        int up = 0; //up=0表示向下,up=1表示向上

        for(char c : s){
            newStr[current] += c; //加到字符串上

            current = up ? current-1 : current+1;  //如果是up,x--,否则x++
            if(current == numRows-1 || current == 0){
                up = !up; //箭头反转
            }
        }

        string str;
        for(string row : newStr){
            str += row;
        }

        return str;      
    }
   
};

学到的总结:

  1. vector : 不要用vector !!!,string更好!

  2. 三元表达式:condition ? expression1 : expression2;

    if (condition){
    	cur = a;
    }else {
    	cur = b;
    }
    ==>
    cur = condition ? a : b
    
  3. 遍历:char c : s

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1003257.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号