1 class Solution { 2 public String convert(String s, int numRows) { 3 String resultS = ""; // 待返回的字符串 4 int len = s.length(); // 字符串长度 5 if (numRows <= 1){ return s;} 6 for(int row = 0 ; row < numRows ; row ++){ 7 int n = 0; // 设置间隔数 8 int index = 0; // 设置读取的索引值 9 if(row == 0 || row == numRows -1){ 10 // 如果处于第0行或最后一行,显示的数据的等差 2*(numRows -1) ,对应累加索引 row + 2*(numRows -1)*n 11 index = row; 12 while ( index < len ){ 13 resultS += s.charAt(index); 14 n ++; 15 index = row + 2*(numRows -1)*n; 16 } 17 }else{ 18 // 如果处于中间行,显示的等差数据为:2*(numRows -1) - 2*row , 2*row , 19 // 对应的累加索引: n 为偶数时 row + (numRows -1) *n ; n 为奇数时 row + 2*(numRows -1) * (n + 1)/2 -2*row 20 index = row; 21 while (index < len){ 22 resultS += s.charAt(index); 23 n ++ ; 24 index = (n % 2 == 0)? (row + (numRows -1) *n) : (row + 2*(numRows -1) * (n + 1)/2 -2*row) ; 25 } 26 27 } 28 29 } 30 return resultS; 31 } 32 }
N字型变换:https://leetcode.cn/problems/zigzag-conversion/submissions/
标签:numRows,String,int,字型,力扣,字符串 From: https://www.cnblogs.com/luyj00436/p/17144011.html