6 ZigZag Conversion
2015-06-15 01:27
239 查看
The string “PAYPALISHIRING” is written in a zigzag(Z字形) pattern on a given number of rows like 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:
Tags:String
input
output
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".
Tags:String
import java.util.*; public class No6 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.next(); int n = scanner.nextInt(); String str = convert(s, n); System.out.println(str); } public static String convert(String s, int n) { if(n==1) return s; int dot = n + n - 2; // 折点 String[] str = new String ; String str1 = ""; for (int a = 0; a < n; a++) { str[a] = ""; } int i = 0; while (dot * i < s.length()) { str[0] += s.charAt(dot * i); i++; } // return str[0]; int dots; for (int j = 1; j < n - 1; j++) { // j表示行数;从第2行到倒数第2行; i = 0; //重置为0; while ((dots = dot * i) < s.length()) { if ((dots + j) < s.length()) { str[j] += "" + s.charAt(dots + j); } if ((dots + dot - j) < s.length()) { str[j] += "" + s.charAt(dots + dot - j); } i++; } } i = 0; // 重置i; while ((n - 1 + dot * i) < s.length()) { str[n - 1] += s.charAt(n - 1 + dot * i); i++; } for (i = 0; i < n; i++) { str1 += str[i]; } return str1; } }
input
abcdefghijklmnopqrstuvwxyz 5
output
aiqybhjprxzcgkoswdflntvemu
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
---|---|---|---|---|---|---|---|---|---|---|---|---|
a0 | i8 | q16 | y24 | |||||||||
b1 | h7 | j9 | p15 | r17 | x23 | z25 | ||||||
c2 | g6 | k10 | o14 | s18 | w22 | |||||||
d3 | f5 | l11 | n13 | t19 | v21 | |||||||
e4 | m12 | u20 |
相关文章推荐
- Linux终端常用快捷键
- Android 异步加载图片,使用LruCache和SD卡或手机缓存,效果非常的流畅
- 杨中科--数学的应用--识别色情图片
- JSP(4) ----servlet 编程1
- 使用Proxy模拟一个最简单的数据库Connection池和PrepareStatment池
- 黑马程序员-Java基础-if、while、for语句
- 讨论着陆页面在搜索引擎上的索引情况
- Android插件化、动态加载及动态更新
- objective-c 键值监听
- 循环链表(4) - 分割链表为两段
- pycharm4.5.1 注册码 破解
- 文件批量改名
- Git连接github不用每次输入用户名和密码的方法
- jQuery 多个条件检索,多条件检索的第一个和$(this)
- MySQL事务控制语句
- 黑马程序员---基础-概述、封装、构造方法、this和static关键字、继承
- base Tag
- 循环链表(3) - 遍历
- WIN8 自定义控件添加到页面XAML报错的解决方法
- 回溯法