ZigZag - 曲折字符串
需求:将所给的字符串以“倒N型”输出,可以指定输出的行数
函数 String convert(String s, int numRows)
例如输入“abcdefghijklnmopqrstuvwxyz”,输出成3行;得到
a e i n q u y
bdfhjlmprtvxz
c g k o s w
下面是一个5行的例子
String s = "abcdefghijklnmopqrstuvwxyzabcdefghijklnmopqrstuvwxyzabcdefghijklnmopqrstuvwxyz";
a___i___q___y___g___o___w___e___n___u
b__hj__pr__xz__fh__mp__vx__df__lm__tv
c_g_k_o_s_w_a_e_i_n_q_u_y_c_g_k_o_s_w
df__lm__tv__bd__jl__rt__zb__hj__pr__xz
e___n___u___c___k___s___a___i___q___y
MD$}1[_C`]]M.png)
便于观察,用下划线代替空格;可以看到行末是没有空格的;
观察例子:
1.从0开始计数,第0行第0列是“a”;第4行第0列是“e”;把位于斜线的字母称为斜线位
2.完整列之间间隔为3,即5-2;对于3行的例子,间隔为1=3-2;2行的例子,间隔为0=2-2;间隔为numRows-2;
3.首行和尾行没有斜线位;观察编号,得知a到i之间间隔2*numRows-2;令zigSpace=2*numRows-2
4.对于空格数量,第0行字母之间有3个空格;第1行斜线位左边有2个空格,右边0个;
第2行斜线位左边1个空格,右边1个;第3行斜线位左边0个空格,右边2个
这里斜线位字符的位置是: 2*numRows-2 + j - 2*i(其中i为行数,j为该行第几个字符)
5.最后一列后面不再添加空格,可用游标是否越界来判断
代码中convertOneLine将结果成从左到右读成一行
/**
* @author Rust Fisher
* @version 1.0
*/
public class ZigZag {
/**
* @param s
* @param numRows
* @return The string that already sort
*/
public static String convert(String s, int numRows) {
if (numRows <= 1 || s.length() < numRows || s.length() < 3) {
return s;
}
String strResult = "";
int zigSpace = 2*numRows - 2;
int zig = numRows - 2;
for (int i = 0; i < numRows; i++) {
for (int j = i; j < s.length(); j+=zigSpace) {
strResult = strResult + s.charAt(j);
if (i != 0 && i != numRows - 1 && (zigSpace + j - 2*i) < s.length()) {
for (int inner = 0; inner < zig - i; inner++) {
strResult += " ";
}
strResult = strResult + s.charAt(zigSpace + j - 2*i);
if ((2*zigSpace + j - 2*i) <= s.length()/*true*/) {//control the final word of string
for (int inner = 0; inner < i - 1; inner++) {
strResult += " ";
}
}
} else {
if (j+zigSpace < s.length()) {//control the final word of per line
for (int outline = 0; outline < zig; outline++) {
strResult += " ";
}
}
}
}
if (i < numRows - 1) {
strResult += "\n";
}
}
return strResult;
}
/**
* @param s
* @param numRows
* @return one line String
*/
public static String convertOneLine(String s, int numRows) {
if (numRows <= 1 || s.length() < numRows || s.length() < 3) {
return s;
}
String strResult = "";
int zigSpace = 2*numRows - 2;
for (int i = 0; i < numRows; i++) {
for (int j = i; j < s.length(); j+=zigSpace) {
strResult = strResult + s.charAt(j);
if (i != 0 && i != numRows - 1 && (zigSpace + j - 2*i) < s.length()) {
strResult = strResult + s.charAt(zigSpace + j - 2*i);
}
}
}
return strResult;
}
public static void main(String args[]){
String s = "abcdefghijklnmopqrstuvwxyzabcdefghijklnmopqrstuvwxyzabcdefghijklnmopqrstuvwxyz";
String ss = "abcdefghijklnmopqrstuvwxyz";
System.out.println(convert(ss,3));
System.out.println(convertOneLine(ss,3));
System.out.println();
System.out.println(convert(s,5));
System.out.println(convertOneLine(s,5));
}
}
输出:
a e i n q u y
bdfhjlmprtvxz
c g k o s w
aeinquybdfhjlmprtvxzcgkosw
a i q y g o w e n u
b hj pr xz fh mp vx df lm tv
c g k o s w a e i n q u y c g k o s w
df lm tv bd jl rt zb hj pr xz
e n u c k s a i q y
aiqygowenubhjprxzfhmpvxdflmtvcgkoswaeinquycgkoswdflmtvbdjlrtzbhjprxzenucksaiqy

但不得不说明的是,上面这种方法太慢了。在网上查到了另一个方法,Java代码如下:
public String convert(String s, int numRows) {
if (s == null || numRows < 1) return null;
if (numRows == 1) return s;
char[] ss = s.toCharArray();
StringBuilder[] strings = new StringBuilder[numRows];
for (int i = 0; i < strings.length; i++) {
strings[i] = new StringBuilder();
}
int zigNum = 2 * numRows - 2;
for (int i = 0; i < s.length(); i++) {
int mod = i % zigNum;
if (mod >= numRows) {
strings[2*numRows - mod - 2].append(ss[i]);
}
else {
strings[mod].append(ss[i]);
}
}
for (int i = 1; i < strings.length; i++) {
strings[0].append(strings[i].toString());
}
return strings[0].toString();
}
利用了StringBuilder类来构建String
ZigZag - 曲折字符串的更多相关文章
- Leetcode 6 ZigZag Conversion 字符串处理
题意:将字符串排成Z字形. PAHNAPLSIIGYIR 如果是5的话,是这样排的 P I AP YR H L G N SI A I 于是,少年少女们,自己去找规律吧 提示:每个Z ...
- [leetcode]6. ZigZag Conversion字符串Z形排列
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...
- LeetCode 6. ZigZag Conversion & 字符串
ZigZag Conversion 看了三遍题目才懂,都有点怀疑自己是不是够聪明... 就是排成这个样子啦,然后从左往右逐行读取返回. 这题看起来很简单,做起来,应该也很简单. 通过位置计算行数: P ...
- Java [leetcode 6] ZigZag Conversion
问题描述: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows ...
- News common vocabulary
英语新闻常用词汇与短语 经济篇 accumulated deficit 累计赤字 active trade balance 贸易顺差 adverse trade balance 贸易逆差 aid 援助 ...
- LeetCode解题录-1~50
[leetcode]1. Two Sum两数之和 Two Pointers, HashMap Easy [leetcode]2. Add Two Numbers两数相加 Math, LinkedLis ...
- 理解StringBuilder
StringBuilder objects are like String objects, except that they can be modified. Internally, these o ...
- [LeetCode] ZigZag Converesion 之字型转换字符串
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...
- LeetCode之“字符串”:ZigZag Conversion
题目链接 题目要求: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of ...
随机推荐
- 可视化之AQICN
上一篇和大家分享了<可视化之Berkeley Earth>,这次看一看下面这个网站---aqicn.org.先做一个提示:文末有惊喜~ 该网站在中国有一定的权威性,PM2.5数据有一点敏感 ...
- Dom元素的Property和Attribute
Attribute就是DOM节点自带的属性,例如html中常用的id.class.title.align等: 而Property是这个DOM元素作为对象,其附加的内容,例如childNodes.fir ...
- mysql之 innobackupex备份+binlog日志的完全恢复(命令行执行模式)
前言:MySQL的完全恢复,我们可以借助于完整的 备份+binlog 来将数据库恢复到故障点.备份可以是热备与逻辑备份(mysqldump),只要备份与binlog是完整的,都可以实现完全恢复. 1. ...
- cpp(第四章)
1.索引比数组长度少1: 2.c++中不能数组赋给另一个数组:只能定义时才能使用初始化: 3.c++11中{}内为空,默认赋值为0,而c++中{}如果只对部分初始化,其他部分将被设置为0:c++11使 ...
- java之内部类
最近学了java,对内部类有一点拙见,现在分享一下 所谓内部类(nested classes),即:面向对象程序设计中,可以在一个类的内部定义另一个类. 内部类不是很好理解,但说白了其实也就是一个类中 ...
- [附录]Discuz X2.5程序模块source功能处理目录注释
/source/admincp后台管理 /source/admincp/cloud云平台项目 /source/admincp/menu后台扩展菜单目录 /source/admincp/moderate ...
- js实现整数转化为小数
toFixed 方法 返回一个字符串,代表一个以定点表示法表示的数字. number .toFixed(i) 参数 bumber 必选项.一个 Number 对象. i 可选项.小数点 后的数字位数. ...
- 深入研究React setState的工作机制
前言 上个月发表了一篇 React源码学习--ReactClass,但是后来我发现,大家对这种大量贴代码分析源码的形式并不感冒.讲道理,我自己看着也烦,还不如自己直接去翻源码来得痛快.吸取了上一次的教 ...
- 活动页怎么切图photoshop
一 切固定大小的单个图片 1.用pc打开图像 2.按ctrl+A(全选) 3.点击 选择 ->变换选区 ->拉参考线(把参考线放到最中央)->按回车 ->ctrl+d(取消全选 ...
- Android 图片加载框架Glide4.0源码完全解析(二)
写在之前 上一篇博文写的是Android 图片加载框架Glide4.0源码完全解析(一),主要分析了Glide4.0源码中的with方法和load方法,原本打算是一起发布的,但是由于into方法复杂性 ...