Leetcode6 Zigzag Conversion
阿新 • • 發佈:2018-11-17
研究其走向,發現,可以構建一個StringBuilder物件陣列,用來存每行的值,(python,c++中可以建多個char陣列),然後在zigzag的斜向邊中所對應的StringBuilder陣列下標可以用Hashmap儲存(python的dict)得到。
import java.util.*; public class ZigzagConversion6 { public String convert(String s, int numRows) { if(numRows==1) return s; StringBuilder[] sb = newStringBuilder[numRows]; Map<Integer,Integer> map = new HashMap<>(); for(int i=0;i<2*numRows-2;i++) { if(i<numRows) map.put(i, i); else map.put(i, 2*numRows-2-i); } for(int i=0;i<numRows;i++) sb[i]=new StringBuilder();for(int i=0;i<s.length();i++) { int j = i%(2*numRows-2); sb[map.get(j)].append(s.charAt(i)); } StringBuilder res = new StringBuilder(); for(int i=0;i<numRows;i++) { res.append(sb[i]); } return res.toString(); } }
時間複雜度O(n),空間複雜度O(n)。69ms,19,97%。第二遍跑30ms,83.07%。按複雜度看,應該是可以的。
學習22ms答案,優化下邊際情況,22ms答案大體思路和我一樣,不過實現細節不同,它直接在輸出的char陣列上操作,以輸出陣列為導向,而我是以輸入字串為導向的。它可以省去Hashmap等不必要的資料結構,在空間複雜度上更優,時間上也更快,時間複雜度倒是基本一致:
class Solution { public String convert(String s, int numRows) { if(numRows==1||s.length()<=1) return s; char[] schar = s.toCharArray(); char[] output = new char[s.length()]; int outputindex = 0; for(int offset=0;offset<numRows;offset++) { int index = offset; if(index>=s.length()) break; output[outputindex++] = schar[index]; while(index<s.length()) { //skip the last row if(offset<numRows-1) { index+=2*(numRows-1-offset); if(index>=s.length()) break; output[outputindex++] = schar[index]; } //skip the first row if(offset>0) { index+=2*offset; if(index>=s.length()) break; output[outputindex++] = schar[index]; } } } return new String(output); } }
18ms,100%。33ms,73.20%。