Leetcode ZigZag Conversion
2016-07-06 00:53
447 查看
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
Difficulty: Easy
public class Solution {
public String convert(String s, int numRows) {
if(s.length() <= numRows || numRows == 1) return s;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < numRows; i++){
if(i == 0 || i == numRows - 1){
int j = i;
while(j < s.length()){
sb.append(s.charAt(j));
j += numRows + numRows - 2;
}
}
else{
int j = i;
while(j < s.length()){
sb.append(s.charAt(j));
j += 2 * (numRows - 1 - (j % (2*numRows - 2)));
if(j >= s.length())
break;
sb.append(s.charAt(j));
j += 2 * (2 * numRows - 2 - (j % (2*numRows - 2)));
}
}
}
return sb.toString();
}
}
"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".
Difficulty: Easy
public class Solution {
public String convert(String s, int numRows) {
if(s.length() <= numRows || numRows == 1) return s;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < numRows; i++){
if(i == 0 || i == numRows - 1){
int j = i;
while(j < s.length()){
sb.append(s.charAt(j));
j += numRows + numRows - 2;
}
}
else{
int j = i;
while(j < s.length()){
sb.append(s.charAt(j));
j += 2 * (numRows - 1 - (j % (2*numRows - 2)));
if(j >= s.length())
break;
sb.append(s.charAt(j));
j += 2 * (2 * numRows - 2 - (j % (2*numRows - 2)));
}
}
}
return sb.toString();
}
}
相关文章推荐
- Windows 下安装Apache web服务器
- APP反编译基本流程
- Leetcode Nim Game
- Linux学习笔记四
- JMS基本概念之一
- Leetcode Longest Substring Without Repeating Characters
- .NET Core初体验 - 在Mac下运行第一个Web示例程序
- Leetcode Reverse Words in a String
- ELK集群故障处理
- 数据结构与算法(每天更新)
- Leetcode Add Two Numbers
- HDU 5289 Assignment(线段树)
- 一种c#深拷贝方式完胜java深拷贝(实现上的对比)
- CMake 介绍 & CMakeList.txt
- 老毛桃U盘启动盘制作工具V20140501完美贡献版
- 老毛桃U盘启动盘制作工具V20140501完美贡献版
- 稳定排序和不稳定排序
- 102. Binary Tree Level Order Traversal
- django-模板初探
- Mac OS X系统下编译运行C代码