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

LeetCode解题报告--ZigZag Conversion

2015-06-02 00:04 459 查看


题目来源:https://leetcode.com/problems/zigzag-conversion/

P AH N

AP LS I I G

YI R

解法一:

间距为: icount = 2 * (nRows - 1)

每列的字符个数为:i = nRows[from 0 to (nRows - 1)]

中间未加粗字符其下标为: mid = j + icount - 2 * i (j : from 0 to s.length() - 1)

public static String convert(String s, int numRows) {
int icount = 2 * (numRows - 1);
String newStr = "";
if(numRows < 2 || s.length() <= 1)
return s;
else{
for(int i = 0;i < numRows;i ++){

for(int j = i;j < s.length();j += icount){
newStr += s.charAt(j);
int mid = j + icount - 2 * i;

if(i != 0 && i != numRows - 1 && mid >= 0 && mid < s.length()){
newStr += s.charAt(mid);
}
}
}
return newStr;
}

}


解法二:

将每层看层一个字符串,则共有nRows字符串,最后将其依次输出即可。

public static String convert(String s, int numRows) {

StringBuffer[] str = new StringBuffer[numRows];
boolean down = true;
int j = 0;
if(s.length() <= 1 || numRows <= 1)
return s;

for(int i = 0;i < str.length;i ++)
str[i] = new StringBuffer();
for(int i = 0;i < s.length();i ++){

str[j].append(s.charAt(i));
if(j == 0)
down = true;
else if(j == numRows - 1)
down =false;
if(down)
j ++;
else
j --;
}
StringBuffer newStr= new StringBuffer();
for(StringBuffer string : str)
newStr.append(string.toString());

return newStr.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息