leetcode6.ZigZag Conversion

leetcode6.ZigZag Conversion

题意:

字符串“PAYPALISHIRING”以给定行数的Z形图案写入,如下所示:(您可能希望以固定字体显示此模式以获得更好的可读性)

思路:

横向对第0行和最后一行做特别的处理,纵向要考虑此时字符串是向上排列还是向下排列。公式由画图易推倒。

ac代码:

C++

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows <= 1) return s;
        string res = "";
        int len = s.length();
        for (int i=0;i<numRows;i++)
        {
            int k = i;
            if(i==0||i==numRows-1)
            {
                while(k < len){
                    res += s[k];
                    k += 2*numRows - 2;
                }
            }
            else
            {
                bool flag = true;
                while(k < len){
                    res += s[k];
                    k += flag?2*(numRows-i-1):2*i;
                    flag = !flag;
                }
            }
        }
        return res;
    }
};

python

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows <= 1:
            return s
        res = ''
        i = 0
        while i < numRows:
            k = i
            if i == 0 or i == numRows - 1:
                while k < len(s):
                    res += s[k]
                    k += 2*numRows - 2
            else :
                flag = True
                while k < len(s):                    
                    res += s[k]
                    k += 2*(numRows - i - 1) if flag else 2*i 
                    flag = not flag
            i += 1
        return res
原文地址:https://www.cnblogs.com/weedboy/p/7146999.html