ZigZag
一、题解
给出字符串helloWorld!java
- 这是3行
从左往右依次是holelWrdlo!
- 这是4行
从左往右依次是hoeWrlol!ld
二、思路
每一行都是独立的字符串,最后拼接起来就ok。
app
三、实现
一、n行即n个String,考虑到字符串常常拼接修改,故使用StringBuiler能大大提升效率。ui
StringBulier[] sb = new StringBuiler[n] //n行
二、观察规律,发现4个一组(红色框框部分)。
因而可知,咱们只需循环红色部分便可。红色部分包含两部分:左侧n个,右侧n-2个。
每个红框部分以下:
spa
for (int i = 0; i < n; i++) { //左侧依次加入String1,String2,...String n sb[i].append(字符串中下标为i对应的字符即str.charAt(i)) } for (int i = n - 2; i > 0 ; i--) { // 从下往上因此要倒着来 // 右侧依次加入String1,String2,...String n sb[i].append(字符串中下标为i对应的字符即str.charAt(i)) }
三、循环红色框框部分便可3d
int index = 0; //对应字符串的下标 while(index < length){ //length为字符串长度 //循环红色框框部分 }
四、细节指针
一、若是传入hello,可是行数比字符串长度还大好比1000行,显然结果仍是hello。 二、若是传入了null或空,则直接返回null或者空。 三、有这样一种状况:如图。 开始第四次循环红框部分时,此时index=13,知足index<length条件。 若是index=16时,它还在while内部循环,此时str.charAt(index)就会抛出空指针异常! 因此在while内部的for循环也要加上index<length的条件。
四、Java代码
若有意见,多多指出!code
public String convert(String text, int nRows) { if (nRows < 1) return null; if (null == text || "".equals(text)) return text ; if (text.length() <= nRows || nRows == 1) return text; char[] chars = text.toCharArray(); int len = chars.length; StringBuilder[] sb = new StringBuilder[nRows]; for (int i = 0; i < sb.length; i++) { sb[i] = new StringBuilder(); } int charIndex = 0; while (charIndex < len) { for (int i = 0; i < nRows && charIndex < len; i++) { sb[i].append(chars[charIndex++]); } for (int i = nRows - 2; i > 0 && charIndex < len; i--) { sb[i].append(chars[charIndex++]); } } StringBuilder res = new StringBuilder(); for (int i = 0; i < sb.length; i++) { res.append(sb[i]); } return res.toString(); }