LeetCode ZigZag Conversion

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".

基本的实现题。不过需要仔仔细细的想想画画分析。设字符串长度为n。比较简单的做法是产生一个(numRows-1)*numRows矩阵把输入字符串按要求扔进去,再逐行遍历。但这么做浪费不少空间,抠门一点换个思路。

以题目中的PAYPALISHIRING为例。我们在纸上构建如下矩阵


不同的颜色的字符串代表一组,其个数为k=2*numRows-2。我以i,j为坐标定位矩阵。0<= i < numRows, 0<=j<=n/k。我们逐行逐列遍历矩阵,在每一个i,j处都可以定位到原矩阵相应字符的位置,依次把该字符加入结果尾部即可。定位公式如下:(1)if i==0 or i==numRows-1, index = i+k*j. 此时每个i,j处只要加入一个字符(2) otherwise,此时每个i,j处要加入两个字符,index1 = i+k*j, index2 = (j+1)*k-(i-1)-1 = (j+1)*k-i。注意对index要判断是否小于n,大于n的舍弃。代码如下

public class Solution {
    public String convert(String s, int numRows) {
        if(s==null) return null;
        int n = s.length();
        if(n==0) return "";
        if(numRows==1 || numRows>=s.length()) return s;
        int k = 2*numRows-2;
        StringBuffer buffer = new StringBuffer();
        //ArrayList<StringBuffer> list = new ArrayList<StringBuffer>();
        for(int i = 0; i<numRows; i++){
            for(int j=0;j<=n/k;j++){
                if(i==0 || i==numRows-1){
                    int index = i + j*k;
                    if(index<n){
                        buffer.append(s.charAt(index));
                    }
                }else{
                    int index1 = i+j*k;
                    int index2 = (j+1)*k-i;
                    if(index1<n){
                        buffer.append(s.charAt(index1));
                    }
                    if(index2<n){
                        buffer.append(s.charAt(index2));
                    }
                }
            }
        }
        return buffer.toString();
    }
}

时间复杂度为O(N),空间复杂度如果不算结果为1.


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值