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;
	}
}


發佈了27 篇原創文章 · 獲贊 13 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章