第27题 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".


Solution in Java:

public class Solution {
    public String convert(String s, int nRows) {
        if(nRows==0 || nRows==1)    return s;
        int numRepeat = 2*nRows-2;  //The number of characters in a zigzag pattern
        int lengthTotal = s.length();   //The length of the original string
        int nLoop = (int)Math.ceil((double)lengthTotal/(double)numRepeat);  //number of loops for the zigzag pattern 
        String[] convertStrings = new String[nRows];    //the array of strings for n rows
        for(int k=0; k<nRows; k++)  convertStrings[k]="";
        
        for(int i=0; i< nLoop-1; i++){
            convertStrings[0]+= s.charAt(i*numRepeat);
            convertStrings[nRows-1] +=s.charAt(i*numRepeat + nRows-1);
            for(int j=1; j< nRows-1; j++){
                convertStrings[j]= convertStrings[j]+  s.charAt(i*numRepeat+ j) + s.charAt((i+1)*numRepeat-j);
            }
        }
        
        //The code for the last loop, which may contain less than numRepeat characters
        convertStrings[0]+= s.charAt((nLoop-1)*numRepeat);
        for(int j=1; j< nRows-1; j++){
            if((nLoop-1)*numRepeat +j < lengthTotal && (nLoop)*numRepeat -j <lengthTotal )
                convertStrings[j]= convertStrings[j]+  s.charAt((nLoop-1)*numRepeat+ j) + s.charAt(nLoop*numRepeat-j);
            else if((nLoop-1)*numRepeat+j<lengthTotal)
                convertStrings[j] += s.charAt((nLoop-1)*numRepeat+j);
        }
        if((nLoop-1)*numRepeat + nRows-1<lengthTotal)
            convertStrings[nRows-1] +=s.charAt((nLoop-1)*numRepeat + nRows-1);
            
            
            
        String converted="";
        for(int k=0; k<nRows; k++){
            converted+= convertStrings[k];
        }
        return converted;
    }
}

Note:在zigzag的pattern下,可以将字符串分为多组,每一组长度为nRows*2-2,既为除了第一行和最后一行,每一行都要经过两遍。建立大小为nRows的String数组,每组保存相对应一行的字符串,遍历整个字符串s,赋值时将该位置的字符串联到相应的行中,最后几行串联为完整的字符串。


字符串和char串联,一样可以用‘+’号。

提取字符串中某一位的char,不能直接用s[index]这种方法,此时s被默认为数组。要用s.charAt(index)函数。

向上取整用Math.ceil(double x)函数,返回值也为double。

注意最后一个loop时要特别处理,因为字符串张度可能不是nRows*2-2的整数倍,这时要检查index是否已超过字符串总长。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值