LeetCode-ZigZag Conversion
阿新 • • 發佈:2018-04-12
static urn stringbu args 鋸齒形 規律 lee ati string
鋸齒形排列
其實就是找到規律就行。
代碼如下:
package com.leetcode.study; public class Main { private int lo,maxLen; public static void main(String[] args) { String s = "AB"; System.out.println(convert(s, 2)); } public static String convert(String s, int numRows){ if(numRows==1)returns; int len = s.length(); if(numRows==2){ StringBuffer sb1 = new StringBuffer(); StringBuffer sb2 = new StringBuffer(); for(int i = 0;i<len;i++){ if(i%2==1)sb1.append(s.charAt(i)); else sb2.append(s.charAt(i)); }return sb2.append(sb1).toString(); } int rows = len%(2*(numRows-1))==0?len/(2*(numRows-1)):1+len/(2*(numRows-1)); StringBuffer sb = new StringBuffer(); for(int i = 0;i<numRows;i++){ if(i==0||i==(numRows-1)){ for(int j = 0;j<rows;j++){if(2*(numRows-1)*j+i<len)sb.append(s.charAt((numRows+1)*j+i)); } }else{ for(int j = 0;j<rows;j++){ if(2*(numRows-1)*j+i<len)sb.append(s.charAt(2*(numRows-1)*j+i)); if(2*(numRows-1)*(j+1)-i<len)sb.append(s.charAt(2*(numRows-1)*(j+1)-i)); } } } return sb.toString(); } }
LeetCode-ZigZag Conversion