LeetCode--ZigZag Conversion
2015-07-04 16:49
267 查看
The string
And then read line by line:
Write the code that will take a string and make this conversion given a number of rows:
问题描述:
给出一个字符串和一个整数numRows,返回得到的zigzag 序列。
解决方法:
找规律,画出当numRows=3,4,5,6时的样子,然后找规律。
通过观察发现,每行起始位置是有后期规律的,彼此间相差span=numRows + (numRows-2)个字符序列;
在非起始行与末尾行中,每个周期都需要加入一个额外的字符,与本次周期起始字符相差 n = numRows + (numRows-2) - i * 2个字符。
程序如下:
"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".
问题描述:
给出一个字符串和一个整数numRows,返回得到的zigzag 序列。
解决方法:
找规律,画出当numRows=3,4,5,6时的样子,然后找规律。
通过观察发现,每行起始位置是有后期规律的,彼此间相差span=numRows + (numRows-2)个字符序列;
在非起始行与末尾行中,每个周期都需要加入一个额外的字符,与本次周期起始字符相差 n = numRows + (numRows-2) - i * 2个字符。
程序如下:
public class Solution { public String convert(String s, int numRows) { if(s.length()<=0 || numRows<=1) return s; String res = ""; int span = numRows + (numRows-2); for(int i=0; i<numRows; i++){ String s1 = new String(); for(int j=i; j<s.length(); j=j+span){ s1 = s1 + s.charAt(j); int span1 = numRows +(numRows-2) -2*i; if(i>0 && i<numRows-1 && j+span1<s.length()){//如果是中间行,需要额外加字符 s1 = s1 + s.charAt(j+span1); } } res = res + s1; } return res; } }
相关文章推荐
- 邓小平经济理论学习捕导
- HTTP 协议详解
- Windows 10的窗口标题栏能换个颜色吗?
- POSIX线程-基本操作
- jquery tmpl 详解
- [数学笔记Mathematical Notes]目录
- 当代世界市场经济模式比较
- openGL学习笔记 简单概念
- char-cnn+torch+ubuntu14.04(RNN)
- 欢迎使用CSDN-markdown编辑器
- POSIX线程-为什么要用线程
- POSIX线程-什么是线程
- 【足迹C++primer】52、,转换和继承虚函数
- 树 树的概念 树的存储结构
- 社会主义市场经济的实践依据
- C++中的namespace
- XML解析
- POSIX线程-条件变量(二)
- Sqoop工具
- Servlet的一些知识