leetcode ZigZag Conversion

265 篇文章 1 订阅
231 篇文章 0 订阅

ZigZag Conversion

 Total Accepted: 5160 Total Submissions: 22837My Submissions

 

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

 

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

 

 

Have you been asked this question in an interview? 


I treat this problem in a direct way:

class Solution {
 public:
  string convert(string s, int nRows) {
    int i, j, flg;
    vector<char> vec;
    vector<vector<char>> zigzag(nRows,vec);
    for (i = 0, j = 0, flg = 1; i < s.length(); ++i) {
      zigzag[j].push_back(s[i]);
      if (flg && j == nRows - 1)
        flg = 0;
      else if (!flg && j == 0)
        flg = 1;
      if (nRows > 1)
        j = flg > 0 ? (j + 1):(j - 1);
    }
    string res = "";
    for (i = 0; i < nRows; ++i)
      for (j = 0; j < zigzag[i].size(); ++j)
        res += zigzag[i][j];
    return res;
  }
};


But a better way is from http://blog.unieagle.net/2012/11/08/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Azigzag-conversion/

class Solution {
 public:
  string convert(string s, int nRows) {
    int len = s.length(), zigSize = nRows*2 - 2, i, j, tmp;
    string res = "";
    if (nRows <= 1) return s;
    for (i = 0; i < nRows; ++i) {
      for (j = i; j < len; j += zigSize) {
        res += s.substr(j,1);
        tmp = j + zigSize - 2 * i;
        if (i != 0 && i != nRows - 1 && tmp < len) {
          res += s.substr(tmp, 1);
        }
      }
    }
    return res;
  }
};


Python Version:

class Solution:
    def convert(self, s, numRows):
        slen = len(s)
        if (numRows <= 1):
            return s
        res = ""
        zigSize = numRows * 2-2
        for i in range(numRows):
            for j in range(i, slen, zigSize):
                res += s[j]
                tmp = j - 2 * i + zigSize
                if (i > 0 and i < numRows-1 and tmp < slen):
                    res += s[tmp]
        return res



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值