6-zigzag-conversion
阿新 • • 發佈:2018-12-16
題目描述:
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 s, int numRows); Example 1:
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2:
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation:
P I N A L S I G Y A H R P I
解決程式碼:
package com.jack.algorithm; /** * create by jack 2018/10/21 * * @auther jack * @date: 2018/10/21 09:05 * @Description: */ public class ZigZagConversion { /** * 題目描述: * https://leetcode.com/problems/zigzag-conversion/ * * @param s * @param numRows * @return */ public static String convert(String s, int numRows) { int length = s.length(); //特殊值的處理 if (length <= numRows || numRows == 0 || numRows == 1) { return s; } //一個週期的鋸齒狀長度,有規律 int z = 2*numRows -2; //二維陣列的列數 int c = (length/z)*(numRows-1); int r = 0; if (length % z > 0) { r = (length%z)/numRows == 0? 1:(1+(length%z)%numRows); c = c+ r; } //建立二維字串陣列,行為numRows,列為c,初始值為:'\0' char[][] chars = new char[numRows][c]; //char [][] chars = new char[numRows][]; //把字串存入二維陣列 //m為商,n為餘數 int m =0,n=0; for (int l = 1,i=0,j=0;l<= length;l++) { char ch = s.charAt(l-1); chars[i][j]=ch; m = l / z; n = l % z; //3,4 if (n!=0 && n < numRows) { i++; } if (n == numRows) { i= i-1; j++; } if (n > numRows || n == 0 ) { i--; j++; } } String rs = display(chars,numRows,c); //輸出二維陣列 return rs; } /** * 把字元陣列轉換為字串 * @param chars * @param r * @param c * @return */ public static String display(char[][] chars,int r,int c){ StringBuilder sb = new StringBuilder(); for (int i=0;i<r;i++) { for (int j=0;j<c;j++) { //判斷是否為預設值,不為預設值的時候才新增字元 if (chars[i][j] !='\0') { sb.append(chars[i][j]); } } } return sb.toString(); } public static void main(String[] args) { //String s1 = "PAHNAPLSIIGYIR"; //String s1 = "PAYPALISHIRING"; //String s1 = "PAYPALISHIRING"; //String s1 = "AB"; String s1 = "PAYPALISHIRING"; //System.out.println("length = "+s1.length()); String s = convert(s1,3); System.out.println(""); System.out.println("s ="+s); } }
程式碼地址: