您的位置:首页 > 编程语言 > Java开发

LeetCode6-ZigZag convert

2017-04-17 15:11 253 查看
【题目】

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"
.
将字符串锯齿状排列后获取其横排重构后的字符串;

【思路】

找规律,发现锯齿状的每一个元素与其所在的行列的关系如下:

0 2r-2 2(2r-2)……
1(2r-2)-1(2r-2)+1(2*(2r-2))-1(2*(2r-2))+1……
2(2r-2)-2(2r-2)+2(2*(2r-2))-2(2*(2r-2))+2……
3(2r-2)-3(2r-2)+3(2*(2r-2))-3(2*(2r-2))+3……
………………………………
r-1(2r-2)-(r-1)(2r-2)+(r-1)(2*(2r-2))-(r-1)(2*(2r-2))+(r-1)……
当numRows=1时,排序后的字符串和排序前的相同
【Java代码】

public class Solution_6_zigzag_convert {
public String convert(String s, int numRows){
String result = "";
if(numRows == 1){
result = s;
return result;
}
for(int i = 0 ; i < numRows&&i < s.length() ; i++){
result += s.charAt(i);
int j = 1;
if(i == 0)
while(j*(2*numRows-2)<s.length())
result += s.charAt(j++*(2*numRows-2));
else if(i == numRows - 1)
while(j*(2*numRows-2)+numRows-1<s.length())
result += s.charAt(j++*(2*numRows-2)+numRows-1);
else{
while(j*(2*numRows-2)-i<s.length()){
result += s.charAt(j*(2*numRows-2)-i);
if(j*(2*numRows-2)+i<s.length())
result += s.charAt(j*(2*numRows-2)+i);
j++;
}
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Zigzag Java