LeetCode 6. ZigZag Conversion(之字形)
2016-05-19 03:47
239 查看
原题网址:https://leetcode.com/problems/zigzag-conversion/
The string
this: (you may want to display this pattern in a fixed font for better legibility)
And then read line by line:
Write the code that will take a string and make this conversion given a number of rows:
return
方法:按照目标顺序直接遍历字符串,逐行生成。
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".
方法:按照目标顺序直接遍历字符串,逐行生成。
public class Solution { public String convert(String s, int numRows) { if (numRows <= 1) return s; char[] sa = s.toCharArray(); char[] zz = new char[sa.length]; int zzpos = 0; int blockSize = numRows * 2 - 2; for(int row = 0; row < numRows; row ++) { for(int pos = row; pos < sa.length; pos += blockSize) { zz[zzpos++] = sa[pos]; int m = pos + (numRows - 1 - row) * 2; if (row > 0 && row < numRows-1 && m < sa.length) zz[zzpos++] = sa[m]; } } return new String(zz); } }
相关文章推荐
- 更换证书后 打包异常 "UUID not found"/ "xxxx描述文件 not found"
- Drupal 登录提示Unrecognized Username and Password. 【已解决】
- 贝叶斯推断--Gibbs Sampling
- LeetCode 5. Longest Palindromic Substring(最长回文子串)
- lua-洗牌算法
- html5无法获取页面的输入值
- 燃尽图
- 在Pythonanywhere上部署Django
- python 的import机制2
- YAML初探
- NYOJ-19-擅长排列的小明
- Xsolla 有15项新功能添加到了4月份的日志中。
- 关于 Java连接sql的转载
- SQL Server删除重复行
- [Ruby笔记]6. Ruby load require 使用对比
- PTA Review of Programming Contest Rules
- 万能的sdk工具!
- Spring 事务机制详解
- JSP+JavaScript实现图片切换
- 百度地图SDK-BaseMapDemo