ZigZag Conversion(Z字型转换)】

【006-ZigZag Conversion(Z字型转换)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题

  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   APLSIIG   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”.

题目大意

  输入一个字符串和指定的行数,将字符以Z字型输出。

解题思路

  计算出字符的最大列数,根据列数和行数创建一个一维数组,再计算每个字符中一维数组中的位置,再对一维数组中的字符进行紧凑操作,返回结果。

代码实现{public String convert(String s, int nRows) {if (s == null || s.length() <= nRows || nRows == 1) {return s;}int index = s.length();(index > 0) {// 竖形的一列index -= nRows;rowLength++;// 斜着的列数for (int i = 0; i < slash && index > 0; i++) {rowLength++;index–;}}(int i = 0; i < result.length; i++) { // 初始化为空格result[i] = ‘ ‘;}int curColumn = 0; // 当前处理的行数index = 0;while (index < s.length()) {// 处理竖线for (int i = 0; i < nRows && index < s.length(); i++) {result[rowLength * i + curColumn] = s.charAt(index);index++;}curColumn++;// 处理斜线for (int i = nRows – 2; i > 0 && index < s.length(); i–) {result[rowLength * i + curColumn] = s.charAt(index);curColumn++;index++;}}= 0;while (index < s.length() && result[index] != ‘ ‘) { // 找第一个是空格的字符位置index++;}int next = index + 1;while (index < s.length()) {while (next < result.length && result[next] == ‘ ‘) { // 找不是空格的元素next++;}result[index] = result[next];index++;next++;}System.out.println(s);System.out.println(new String(result, 0, index));return new String(result, 0, index);}}评测结果

  点击图片,鼠标不释放,,拖动一段位置,释放后在新的窗口中查看完整图片。

特别说明欢迎转载,转载请注明出处【】

喜欢真实的人,要做真实的人,所以从来不会想要刻意模仿任何人。

ZigZag Conversion(Z字型转换)】

相关文章:

你感兴趣的文章:

标签云: