LeetCode 6. ZigZag Conversion

leetcode   题目

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


这个刚开始我还懵b--什么是zig形状啊。。。。

于是我搜索了一下,原来是这样:

偶,这样啊......看着就像求一个循环结构(就是一个形状不断重复)---然后求原数组元素在新的排列规则下的位置。那就求呗(高中数学题,有没有这感觉)

然后我先求竖的:j=step;//step代表他是一个周期内的第几个元素j代表该元素在新的n个String【indes】中的index;

斜的:j=2*numRows-step;


于是代码如下:

public class Solution{
	public String convert(String s,int numRows){
		if(numRows==1)
			return s;
		int k=numRows*2-2;
		String[] res=new String[numRows];
		for(int i=0;i<res.length;i++){
			res[i]="";
		}
		int step=0;
		int j=0;
		for(int i=0;i<s.length();i++){
			step++;
			if(step<=numRows){
				j=step;
			}else{
				j=2*numRows-step;
			}
			res[j-1]+=subString(i,i+1);
			if(ste==k)
				step=0;
		}
		String result="";
		for(String str:res){
			result+=str;
		}
		return result;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值