【LeetCode】006.ZigZag Conversion
来源:互联网 发布:win10怎么装mac系统 编辑:程序博客网 时间:2024/05/22 13:04
题目如下:
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 NA P L S I I GY I RAnd 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"
解答:
解答这道题需要仔细观察。想象为nRows层楼,每层一个住户等待收快递,快递小哥(好比圣诞老人),乘坐电梯,从1层到nRows层,每次1层,每层发一个包裹,到顶层后再往下发,依次类推,直到发完为止。加入快递发的是字符串,每次发1个字符,发完后,从顶至底的住户把收到的字符快递连接在一起,就得到了ZigZag Conversion。
有一个细节还需要注意,如果nRows等于1,就不必再处理了。代码实现时处理不当会导致异常。
代码如下:
public class Solution { public String convert(String s, int nRows) { if(nRows == 1) return s; // in case ArrayIndexOutBoundExceptionArrayList<String> als = new ArrayList<String>();int ind = -1,tag = 1;for(int i=0;i<nRows;i++){als.add(new String(""));}for(int i=0;i<s.length();i++){ind += tag;String cur = als.get(ind).concat(s.substring(i, i+1));als.set(ind, cur);if(ind == nRows - 1)tag = -1;else if(ind == 0){tag = 1;}}String ret = "";for(int i=0;i<als.size();i++){ret = ret.concat(als.get(i));}return ret;}}
0 0
- LeetCode 006. ZigZag Conversion
- 【LeetCode】006.ZigZag Conversion
- leetcode--006. ZigZag Conversion
- 【LeetCode】 006. ZigZag Conversion
- 【LeetCode】006.ZigZag Conversion
- Leetcode Algorithm 006. ZigZag Conversion
- [LeetCode 解题报告]006.ZigZag Conversion
- LeetCode: ZigZag Conversion
- LeetCode : ZigZag Conversion
- leetcode 13:zigzag conversion
- [LeetCode] Zigzag Conversion
- LeetCode 6 - ZigZag Conversion
- Leetcode : ZigZag Conversion
- 【leetcode】Zigzag Conversion
- [LeetCode]ZigZag Conversion
- leetcode ZigZag Conversion
- LeetCode-ZigZag Conversion
- LeetCode ZigZag Conversion
- saleforce中ActionFunction和SupportFunction的区别
- [转载]chrome developer tool 调试技巧
- Vim常用命令
- 程序员的十大无奈
- 生产guid
- 【LeetCode】006.ZigZag Conversion
- 为什么中国的程序员总被称为码农?
- DX11之D3DXMatrixIdentity 函数
- 虚拟机无法连接网络
- 日经社説 20150326 食品の機能性表示どう生かす
- 程序员跳槽注意事项
- 程序员讨厌没有价值的任务
- 一致性hash算法 java实现
- android connection to ip refused