云服务器

商务合作:179001057@qq.com

leetcode-6. ZigZag Conversion

xiaoxiao2021-09-17  28


某平台价值19860元的编程课程资料免费领取【点我领取】


leetcode-6. ZigZag Conversion

题目:

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”.

我看到这题的时候想的比较简单,就是用几个StringBuilder存一下每一行的值,然后组合在一起输出就行。这样做肯定要慢一些的。因为String方面的操作本身就很慢。如果可以用一个StringBuilder直接做肯定做肯定要快一些,或者用一个char[]做应该会更快。不过都是同一个数量级的没必要这么麻烦了。

我的解法

public class Solution { public String convert(String s, int numRows) { if(numRows < 2) return s; StringBuilder[] sbl = new StringBuilder[numRows]; for(int i = 0 ; i < sbl.length ; i++) sbl[i] = new StringBuilder(); boolean flag = true; for(int i = 0,j = 0 ; i < s.length() ;){ if(flag) sbl[j++].append(s.charAt(i++)); else sbl[j--].append(s.charAt(i++)); if(j == numRows-1 || j == 0) flag = !flag; } String ret = ""; for(StringBuilder sb : sbl) ret += sb; return ret; } }

用一个StringBuilder,然后指针计数的方法。

public String convert(String s, int numRows) { if(numRows < 2 || numRows >= s.length()) return s; StringBuilder sb = new StringBuilder(s.length()); int origStep = numRows * 2 - 2; int step = origStep; for(int i = 0; i < numRows; i++){ step = i == numRows - 1 ? origStep : origStep - i * 2; int curr = i; while(curr < s.length()){ sb.append(s.charAt(curr)); curr += step; int temp = Math.abs(step - origStep); step = temp == 0 ? origStep : temp; //First/last rows } } return sb.toString(); }

解法来源