当前位置: 移动技术网 > IT编程>脚本编程>Python > 字形变换(简单模拟和按列访问)

字形变换(简单模拟和按列访问)

2020年11月20日  | 移动技术网IT编程  | 我要评论
6. Z 字形变换题目链接这道题直接简单模拟,先放进一个二维数组然后按行访问数组即可。官方题解:用的按行排序和按行访问由于官方没有python版本,我这里给出官方题解的python版本简单模拟方法:class Solution {public: string convert(string s, int numRows) { if(numRows == 1) return s; vector<vector<char>&g

6. Z 字形变换

题目链接
在这里插入图片描述
在这里插入图片描述
这道题直接简单模拟,先放进一个二维数组然后按行访问数组即可。
官方题解:用的按行排序和按行访问
由于官方没有python版本,我这里给出官方题解的python版本
 
简单模拟方法:

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows == 1) return s;
        vector<vector<char>> v(numRows);
        int j = 0, i = 0;
        int flag = 1;//flag控制方向
        while(i < s.size())
        {
             v[j].push_back(s[i]);
             i++;
            if(j >= numRows-1)//到达边界改变方向
                flag = 0;
            if(j <= 0) flag = 1;
            if(flag == 1)
                j++;//向下则加
            else j--; //向上则减   
            
        }
        string ans = "";
        for(int i = 0; i < numRows; i++)
        {
            for(int j = 0; j < v[i].size(); j++)
            {
                ans += v[i][j];//按行访问二维数组
            }
        }
        return ans;       
    }
};

在这里插入图片描述

python3按行排序:

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows == 1:
            return s
        list1 = ['']*numRows
        curRow = 0
        goingDown = False
        for c in s:
            list1[curRow] += c
            if curRow == 0 or curRow == numRows-1:
                goingDown = not goingDown
            curRow += 1 if goingDown else -1
        ans = ''
        for row in list1:
            ans += row
        return ans

在这里插入图片描述
python3按行访问:

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows == 1:
            return s
        ret = ''
        n = len(s)
        cycleLen = 2*numRows - 2
        for i in range(0, numRows):
            for j in range(0, n-i, cycleLen):
                ret += s[j+i]
                if i != 0 and i != numRows - 1 and j + cycleLen - i < n:
                    ret += s[j + cycleLen - i]
        return ret


在这里插入图片描述

如果对你有帮助的话,请点个赞哦!

本文地址:https://blog.csdn.net/qq_41946404/article/details/109880328

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网