国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

ZigZag Conversion-LeetCode

2019-11-08 01:35:51
字體:
供稿:網(wǎng)友

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   NA P L S I I GY   I   RAnd 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".

Subscribe to see which companies asked this question.

題目理解:將輸入的字符串,字符順序重排后輸出,可以簡單理解為將一維向量轉(zhuǎn)換為了二維的矩陣,最后將二維矩陣又拼接成一維向量返回。重排規(guī)則:zigzag,之字形掃描。解決的大體思路:根據(jù)輸入的之子寬度參數(shù)nRows,將text不同下標(biāo)的字符散列到不同行的字符串中,最后按行重新拼接起來。為了方便追加字符,每一行使用的是StringBuilder result[nRows]。eg:
0   8   16   
1  79  1517   
2 6 10 14 18   
35  1113  19   
4   12   20   
具體的將,再散列字符到不同行時(shí),有兩種思路可以考慮:(1)根據(jù)輸入的nRows,將text分組,在組內(nèi)有相同位置的字符會(huì)被追加到同一行字符中。如上圖所示,nRows=5,那么每組的長度為2*5-2=8;可以看到每8個(gè)字符都是一組相同的形狀和散列位置排布。我們計(jì)算組內(nèi)每個(gè)字符應(yīng)當(dāng)放入哪行字符串,同時(shí)完成向result[]散列的過程。注意到,在同一組內(nèi),字符放入result[]的行號會(huì)有增加和減小兩個(gè)過程。在使用本思路精確計(jì)算式應(yīng)當(dāng)注意。代碼:
public class Solution {	public String convert(String s, int numRows) {		StringBuilder[] result=new StringBuilder[numRows];		char[] array=s.toCharArray();		for(int i=0;i<numRows;i++)result[i]=new StringBuilder(s.length());		//對每一個(gè)stringbulider初始化		int i=0,loc=0;		while(i<s.length()){			for(loc=0;loc<numRows && i<s.length();i+=1,loc+=1){				result[loc].append(array[i]);			}//由0開始的行號上升過程,同時(shí)字符串指示下標(biāo)也要移動(dòng)			for(loc=numRows-2;loc>0 && i<s.length();i+=1,loc-=1){				result[loc].append(array[i]);			}//由numRows-2開始的行號下降過程,同時(shí)字符串指示下標(biāo)也要移動(dòng)		}		for(i=1;i<numRows;i++){			result[0].append(result[i]);		}		return result[0].toString();	}}(2)注意到,在字符散列進(jìn)result[]的行號會(huì)有增加和減小兩個(gè)過程,利用邊界值0和nRows-1,來改變待散列指示標(biāo)記loc的移動(dòng)方向,即可完成正確散列。值得注意的是,使用該思路需要留意nRows為1的情況,需要在代碼的最開始做出特殊情況處理。代碼:
public class Solution {	public String convert(String s, int numRows) {		if(s.length()<=numRows||numRows==1)return s;		StringBuilder[] result=new StringBuilder[numRows];		char[] array=s.toCharArray();		int len=s.length();		for(int i=0;i<numRows;i++)result[i]=new StringBuilder(len);		int i=0,loc=0,step=1;		while(i<len){				result[loc].append(array[i]);			if(loc==numRows-1)step=-1;	//下標(biāo)減小			if(loc==0)step=1;			//下標(biāo)增加			loc+=step;			i+=1;		}		for(i=1;i<numRows;i++){			result[0].append(result[i]);		}		return result[0].toString();	}}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 马边| 浪卡子县| 东乡族自治县| 周宁县| 和林格尔县| 桦川县| 嘉定区| 上杭县| 双城市| 石屏县| 桐城市| 体育| 延津县| 曲麻莱县| 罗江县| 庆阳市| 玛沁县| 宁南县| 盐津县| 唐海县| 棋牌| 张家口市| 澄迈县| 廉江市| 琼海市| 石狮市| 汾阳市| 屏山县| 南陵县| 鄂温| 黎川县| 阜新市| 江安县| 凤庆县| 永寿县| 安顺市| 肥西县| 巴里| 沂源县| 长泰县| 万山特区|