(java)leetcode-6
来源:互联网 发布:陕钢集团网络大学 编辑:程序博客网 时间:2024/06/03 12:28
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 NA P L S I I GY 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"
.
解题思路:
zigzag算法是将一个字符串转成zigzag格式的东西。转的顺序大概是这样的(下图中nRows=4):
然后写入的时候是这样写入的: 1 7 13 19 2 6 8 12 14 18 3 5 9 11 15 17 4 10 16
我的想法是按照nRows从0到3行来读数据,当在第0行和第3行的时候,s中每隔6个数读一个字符(sublen = nRows*2-2),在其他行(i)中,在每隔6个数中读两个数据(j和j+sublen-2*i),这样相当于一次遍历数组就能得到结果。
注意问题:
(1)当nRows == 1时,sublen设为1
(2)主要不要超过s.length()
public class Solution { public String convert(String s, int numRows) { String result = "";int sublen = numRows*2-2;if(sublen == 0)sublen = 1;int len = s.length();for (int i = 0;i<numRows;i++){int j = i;while(j<len){result += s.charAt(j);if(numRows >1 && i%(numRows-1) != 0){int index = j+sublen-2*i;if(index <len)result += s.charAt(index);}j += sublen;}}return result; }}
0 0
- (java)leetcode-6
- [LeetCode Java] 6 ZigZag conversion
- LeetCode 6 : ZigZag Conversion (Java)
- LEETCODE 6 ZigZag Conversion JAVA
- LeetCode[6] ZigZag Conversion(java)
- leetcode#6-ZigZag Conversion-java
- Leetcode(java)
- leetcode java
- 【leetcode with java】6 ZigZag Conversion
- [LeetCode]Next Permutation java leetcode
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- [Leetcode] ZigZag Conversion (Java)
- [Leetcode] Reverse Integer (Java)
- [Leetcode] Palindrome Number (Java)
- [Leetcode] Valid Parentheses (Java)
- [Leetcode] Generate Parentheses (Java)
- [Leetcode] Remove Element (Java)
- 【汇总】 python异常
- 博为峰JavaEE技术文章 ——MyBatis 递归查询
- 【原创】 linux-python-redis…
- 【翻译】python日志logging模块
- 【原创】 linux-python …
- (java)leetcode-6
- 【原创】 python django…
- Linux 常用操作命令
- 【原创】 linux-python …
- 【原创】 python django…
- 【原创-转载-翻译-未完】 pyt…
- 【原创】 python django…
- 计算直线的交点方案数
- c# vs2010 directsound&…