首页 > 代码库 > ZigZag Conversion
ZigZag Conversion
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 NA P L S I I GY 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"
.
简单来说就是把一个字符串变成一个倒Z字形,然后一行一行输出
public class Solution { public String convert(String s, int nRows) { ArrayList<ArrayList<String>> allList = new ArrayList<ArrayList<String>>();//用于存放ZigZag后的二维字符数组 char[] char_array = s.toCharArray(); int size = char_array.length;//字符总长度 if(size<=nRows||nRows==1){ return s; } for(int i=0;i<nRows;i++){//初始化allList ArrayList<String> list = new ArrayList<String>(); allList.add(list); } int x = 0,y = 0;//二维坐标(初始点为(0,0)) int stepX = 0,stepY = 1;//2个坐标上的增量 int value = http://www.mamicode.com/2*nRows-2; for(int n=0;n<size;n++){ String letter = String.valueOf(char_array[n]); allList.get(y).add(letter); if(n%value =http://www.mamicode.com/= 0){ stepX = 0; stepY = 1; } else if(n%value =http://www.mamicode.com/= nRows-1){ stepX = 1; stepY = -1; } y = y+stepY;//跟新坐标 } String result = ""; for(int j=0;j<nRows;j++){ ArrayList<String> lists = allList.get(j); for(String list:lists){ result = result+list; } } return result; }}
ZigZag Conversion
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。