letcode 6 z字转换
很容易想到暴力求解. 这里要注意的是, 静态方法不能新建内部类实例.
class zigC implements Comparable<zigC>{ public zigC(char c, int row, int col) { this.c = c; this.row = row; this.col = col; } char c; int row; int col; @Override public int compareTo(zigC o) { if(this.row!=o.row){ return Integer.compare(this.row,o.row); }else{ return Integer.compare(this.col,o.col); } } } public static String convert(String s, int numRows) { int len = s.length(); ArrayList<zigC> zs = new ArrayList<zigC>(); int row=0; int col=0; int dir=1; for(int i=0;i<len;i++){ if((row==numRows)){ dir=-dir; row-=2; } if(row==-1){ dir=-dir; row+=2; } if(dir==1){ zigC tmp = new zigC(s.charAt(i),row++, col); zs.add(tmp); }else{ zigC tmp = new zigC(s.charAt(i),row--,col++); zs.add(tmp); } } StringBuilder res = new StringBuilder(len); Collections.sort(zs); for (zigC z:zs) { //System.out.print(z.c); res.append(z); } return res.toString();
}
其实可以不用结构体,直接z字形遍历就行
public static String solve(String s, int numRows){ int len = s.length(); if(numRows>len||numRows==1) return s; ArrayList<StringBuilder> z = new ArrayList<>(); for(int i=0;i<numRows;i++){ z.add(new StringBuilder()); } int dir=-1; int row=0; for(int i=0;i<len;i++){ if(row==0||row==numRows-1) dir=-dir; z.get(row).append(s.charAt(i)); row+=dir; } StringBuilder res = new StringBuilder(len); for(StringBuilder ss:z){ res.append(ss); } return res.toString(); }
还有一种更牛的做发,直接找到规律:
作者:LeetCode
链接:https://leetcode-cn.com/problems/zigzag-conversion/solution/z-zi-xing-bian-huan-by-leetcode/
public static String convert(String s, int numRows) { if (numRows == 1) return s; StringBuilder ret = new StringBuilder(); int n = s.length(); int cycleLen = 2 * numRows - 2; for (int i = 0; i < numRows; i++) { for (int j = 0; j + i < n; j += cycleLen) { ret.append(s.charAt(j + i)); if (i != 0 && i != numRows - 1 && j + cycleLen - i < n) ret.append(s.charAt(j + cycleLen - i)); } } return ret.toString(); }