您的位置:首页 > 其它

【leetcode】Zigzag Z 字形变换

2019-01-29 10:17 399 查看
[code]class Solution {
public String convert(String s, int numRows) {
//null check
if(null==s){
return null;
}
if(null!=s &&(s.length()<=1||numRows==1) ){
return s;
}
//calc collumn size we need
int len=s.length();
int innerSize=numRows-2;
int group=(len/(numRows+innerSize));
int colNums=group+(len-numRows*group);
char[][] out=new char[numRows][colNums];
//set value for 2d Array
int tmpCol=0;
int tmpRow=0;
for (int i=0; i<len;i++){
char tmp=s.charAt(i);
int index= i%(numRows+innerSize);
if(index==0){
tmpRow=0;
}
if((i>0&&index==0 )||(index>numRows-1)){
tmpCol++;
}
out[tmpRow][tmpCol]=tmp;

if(index<numRows-1){
tmpRow++;
}else{
tmpRow--;
}

}
StringBuilder stringBuilder=new StringBuilder();
for (int i=0;i<numRows;i++){
for (int j=0;j<colNums;j++){
char c=out[i][j];
if((int)c!=0){
stringBuilder.append(c);
}
}
}

return  stringBuilder.toString();

}

}

Runtime: 64 ms, faster than 8.27% of Java online submissions for ZigZag Conversion.

and

执行用时: 163 ms, 在ZigZag Conversion的Java提交中击败了5.11% 的用户 

本人先讲自己比较笨的 方法

[code]package homework;

public class Main {
public String convert(String s, int numRows) {
int length = s.length(), x = 0, y = 0;
String arr[][] = new String[numRows][20];
int i = 0;
if(numRows==1) {//这个部分是自己后面加上去的 因为numRow==1的话 else部分不适合
return s;
}
else {	//方法的话 是采用 二维数组进行存放
while (i < length) {
arr[x][y] = String.valueOf(s.charAt(i));//先第一步处理竖
// System.out.print(s.charAt(i)+" ");//查看每一步处理的字符串
// System.out.println(arr[x][y]);
i++;
x++;
if (x == numRows - 1) {//竖处理完之后 跳入这个循环 处理斜的 处理完斜行后跳出来
while (x != 0 && i < length) {
arr[x][y] = String.valueOf(s.charAt(i));
// System.out.print(s.charAt(i)+" ");
// System.out.println(arr[x][y]);
x--;
y++;
i++;

}
}
}
}
String str = "";//这个没什么好说的就读数据
for (int i2 = 0; i2 < numRows; i2++) {
for (int x2 = 0; x2 < 20; x2++) {
if (arr[i2][x2] != null && arr[i2][x2] != "")
str = str + arr[i2][x2];
}

}

return str;
}

public static void main(String[] args) {//测试用例
Main m = new Main();
String s = "AB";
int numRows = 1;
System.out.println(m.convert(s, numRows));
}
}

 

 

[code]class Solution {
public String convert(String s, int numRows) {
//如果是有一行,可以直接返回
if (numRows == 1) {
return s;
}
StringBuilder result = new StringBuilder();
//运用数学规律,逐行取值
for (int i = 0; i < numRows; i++) {
int j = 0;//表示第i行的第j个数
while (j + i < s.length()) {
result.append(s.charAt(j + i));//j每次循环时,首先取j+i坐标上的字母
//如果不是第一排或者最后一排,一般情况下,每两个竖排间会有两个字母,第二个字母的规律是j+numRows * 2 - 2 - i
if (i != 0 && i != numRows - 1 && j + numRows * 2 - 2 - i < s.length()) {
result.append(s.charAt(j + numRows * 2 - 2 - i));
}
//第一竖排和第二竖排的坐标差值为numRows * 2 - 2
j += numRows * 2 - 2;
}
}
return result.toString();
}
}

其他解法到leetcode看看   

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: