欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-07 23:50:37
6. Z 字形变换题目链接这道题直接简单模拟,先放进一个二维数组然后按行访问数组即可。官方题解:用的按行排序和按行访问由于官方没有python版本,我这里给出官方题解的python版本简单模拟方法:class Solution {public: string convert(string s, int numRows) { if(numRows == 1) return s; vector&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