如题
一眼看上去两种思路,一种是直接模拟,用二维数组实现。另一种就是直接找规律了
先来简单的找规律
public static String convert(String s, int numRows) {if(numRows==1) {return s;}char [] chs = new char[s.length()];int index = 0;//chs的赋值位indexint t = 2*numRows-2;//相邻完整列同一行的索引之差int i1=0;while(t*i1<s.length()) {//第一行的赋值chs[index]=s.charAt(t*i1);index++;i1++;}for(int i =1;i<numRows-1;i++) {//中间部分需要赋值两个int i2=0;while(i+t*i2<s.length()) {chs[index]=s.charAt(i+t*i2);index++;if((i2+1)*t-i<s.length()) {//相邻完整列间值赋值chs[index]=s.charAt((i2+1)*t-i);index++; //(i2+1)*t-i =i+t*i2+(2*(num-i-1)-1)}i2++;//注意i2++应当在中间值赋值之后}}int i3=0;while(numRows-1+t*i3<s.length()) {//最后一行的赋值chs[index]=s.charAt(numRows-1+t*i3);index++;i3++;}return String.valueOf(chs);}
分为3部分来看 第一行,中间部分和最后一行,应该不难理解
模拟的也来一个吧
public static String convert1(String s, int numRows) {if (numRows == 1) {return s;}char[][] data = new char[s.length() / 2 + 1][numRows];//+1应对单个字符int x = 0;//赋值列数int y = 0;//赋值行数int flag = 0;//赋值方向 0下1上for (int i = 0; i < s.length(); i++) {if (y == 0) {//第一行data[x][y] = s.charAt(i);flag = 0;y++;} else if (y == numRows - 1) {//最后一行data[x][y] = s.charAt(i);flag = 1;x++;y--;} else if (flag == 0) {//中间向下data[x][y] = s.charAt(i);y++;} else {//中间向上data[x][y] = s.charAt(i);x++;y--;}}String st = "";for (int m = 0; m < numRows; m++) {for (int n = 0; n < data.length; n++) {if (data[n][m] != 'u0000')//不是默认值st = st + data[n][m];}}return st;}
很显然效率会不好看
本文发布于:2024-01-28 01:28:10,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17063764983838.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |