問題:
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 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".
大意:
字符串 "PAYPALISHIRING" 被根據(jù)給出的數(shù)字以 zigzag 模式寫成了下面的樣子:(你可能想要用固定的字形來達(dá)到更好的可讀性)
P A H N
A P L S I I G
Y I R一行行讀起來就是:"PAHNAPLSIIGYIR"
寫代碼獲取字符串并根據(jù)給出的行數(shù)作出這種轉(zhuǎn)換:string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) 應(yīng)該 return "PAHNAPLSIIGYIR".
思路:
這道題的意思就題目來看其實不太好理解谒撼,這里借用別人畫的一張圖就能一目了然了:
如圖瞒爬,行數(shù)就是給出的數(shù)字票渠,按照圖中的數(shù)字順序?qū)⒃镜淖址幸粋€個字符去按照循環(huán)對角的結(jié)構(gòu)放置。
而題目要求返回一行行讀下來的字符串魂迄。
如果找規(guī)律去找各個字符所在的位置還比較難的,比較好的方法是根據(jù)行數(shù)創(chuàng)建多個字符串,然后將給出的字符串中的字符按照順序去一個個放置,這里就循環(huán)地利用兩個循環(huán)术瓮,一個是豎著下來,一個是斜著上去匾嘱。最后再將這些字符串一個個拼接成一個完整的字符串斤斧,就出來了。
代碼中我用的是直接 + 的方式來拼接字符串霎烙,這個效率其實比較低撬讽,如果要提高速度,建議使用StringBuffer來做悬垃,但是為了代碼可讀性游昼,還是用 + 來展示,這個點知道就好了尝蠕。
代碼(Java):
public class Solution {
public String convert(String s, int numRows) {
String[] row = new String[numRows];
for (int k = 0; k < numRows; k++) row[k] = "";
int i = 0;
int j = 0;
int gap = numRows-2;
while (i < s.length()) {
for (j = 0; j < numRows && i < s.length(); j++) row[j] += s.charAt(i++);
for (j = gap; j > 0 && i < s.length(); j--) row[j] += s.charAt(i++);
}
String result = "";
for (int k = 0; k < numRows; k++) result += row[k];
return result;
}
}
合集:https://github.com/Cloudox/LeetCode-Record