ZigZag Conversion2015年6月23日
题目:
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 A P L S I I G 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".
思路:
1、通过字符串的长度和numRows大小算出商和余数
2、通过商和余数判断每一行元素的个数,各行元素个数存放在int[] row
3、逐行对应出每一行元素在源字符串中的位置,并根据位置取出相应字符添加到返回字符串的末尾
解答:
1158 / 1158 test cases passed. Status: Accepted Runtime: 372 ms Submitted: 2 minutes ago
public class Solution { public String convert(String s, int numRows) { StringBuilder result = new StringBuilder(""); int len = s.length(); if(numRows == 1 || len<=numRows){ return s; } int quotient = len / (2*numRows -2); int remainder = len % (2*numRows -2); int[] row = new int[numRows]; //求数组row for(int i=0; i<numRows; i++){ if(i==0){ if(remainder > i) { row[i] = quotient + 1; }else{ row[i] = quotient; } }else if(i == numRows -1){ if(remainder > i) { row[i] = quotient + 1; }else{ row[i] = quotient; } }else{ if(remainder > i && remainder <= numRows) { row[i] = 2*quotient + 1; }else if(remainder > numRows){ if((remainder - numRows) >= (numRows-1-i)){ row[i] = 2*quotient + 2; }else{ row[i] = 2*quotient + 1; } }else{ row[i] = 2*quotient; } } } //逐行取出源字符串对应位置的字符添加到result for(int i=0; i<numRows; i++) { if(i==0 || i==numRows-1){ for(int j=0; j<row[i]; j++ ){ result.append(s.charAt(i+j*(2*numRows-2))); } }else{ for(int j=0; j<row[i]; j++ ){ if(j%2==0){ result.append(s.charAt(i+j/2*(2*numRows-2))); }else{ result.append(s.charAt(i+(j-1)/2*(2*numRows-2)+2*numRows-2-2*i)); } } } } return result.toString(); } }