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为输入行数,i为行号

观察图像寻找规律。

如果是第0行和最后一行每个字符之间的距离为2*n-2

如果是中间行,若该行列号为偶数则与下个字符距离2*(n-i-1) ,否则若为奇数则与下个字符相距离2*i


例如:

图中所示,第1行,第一个字符为1,列号为0,为偶数,则与第二个距离为2*(5-1-1)=6

即下个字符为6+1=7

由于7的字符列号为3为奇数,所以下个字符的列号距离为2*1=2 即7+2=9


public class Solution {
    public String convert(String s, int nRows) {
    	
    	String res="";
    	int len=s.length();
    	
    	if (nRows <= 1 || len == 0 ||len<nRows)   //判断行数及字符长度是否不符合
            return s;  

         
        for(int i=0;i<nRows;i++)
        {
            int index = i;
            res +=s.charAt(index);
        	boolean flag = true;//偶数
            for(int k=0;index<len;k++)
            {
                if(i==0||i==nRows-1) //使用公式1
                {
                    index +=2*nRows - 2;
                }
                
                else{ //中间数字使用公式2
                    if(flag) //偶数
                    {
                    	index+=2*(nRows-1-i);     
                        flag = false;
                    }
                    else{
                    	index+=2*i;
                    	flag =true;
                    }
                }
                
                if(index<len)//判断是否超出界限,若不超出则加入
                    res+=s.charAt(index);
            }
        }
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值