ZigZag Conversion leetcode java
題目:
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".
?
題解:
?這道題就是看坐標的變化。并且需要分塊處理。
?n=2時,字符串坐標變成zigzag的走法就是:
?0 2 4 6
?1 3 5 7
?n=3時的走法是:
?0???? 4???? 8
?1? 3 5? 7 9
?2 ? ? 6? ? 10 
?n=4時的走法是:
?0????? 6??? ??? 12
?1?? 5 7??? 11 13
?2 4?? 8 10??? 14
?3 ? ?? 9 ? ? ? ? 15 
?
?可以發(fā)現(xiàn)規(guī)律,畫紅色的長度永遠是 2n-2 (想法是你試想把所有這些行壓縮成兩列,兩邊手擠一下,第二列永遠的第一行和最后一行少字)。
?利用這個規(guī)律,可以按行填字,第一行和最后一行,就是按照2n-2的順序一點點加的。
?其他行除了上面那個填字規(guī)則,就是還要處理斜著那條線的字,可以發(fā)現(xiàn)那條線的字的位置永遠是當前列j+(2n-2)-2i(i是行的index)。 
?按照上面的規(guī)律就可以寫出代碼了。
?代碼如下:
?1?public?String?convert(String?s,?int?nRows)?{???2?????????if(s?==?null?||?s.length()==0?||?nRows?<=0)??
?3?????????????return?"";??
?4?????????if(nRows?==?1)??
?5?????????????return?s;
?6?????????????
?7?????????StringBuilder?res?=?new?StringBuilder();??
?8?????????int?size?=?2*nRows-2;??
?9?????????for(int?i=0;i<nRows;i++){??
10?????????????for(int?j=i;j<s.length();j+=size){??
11?????????????????res.append(s.charAt(j));??
12?????????????????if(i?!=?0?&&?i?!=?nRows?-?1){//except?the?first?row?and?the?last?row
13?????????????????????int?temp?=?j+size-2*i;
14?????????????????????if(temp<s.length())
15?????????????????????????res.append(s.charAt(temp));
16?????????????????}
17?????????????}??????????????????
18?????????}??
19?????????return?res.toString();??
20?????}?
?Reference:http://blog.unieagle.net/2012/11/08/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Azigzag-conversion/
?
轉(zhuǎn)載于:https://www.cnblogs.com/springfor/p/3889414.html
總結
以上是生活随笔為你收集整理的ZigZag Conversion leetcode java的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 计组之总线:4、总线标准
- 下一篇: (王道408考研操作系统)第五章输入/输
