ZigZag Conversion
来源:互联网 发布:北京程序员过剩 编辑:程序博客网 时间:2024/05/20 23:36
The string "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 NA P L S I I GY I RAnd 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"
.
这个题目实际上是一个循环的问题,主要是通过循环规律找到字符串下标,先计算出第一个Z的V部分然后通过他们之间的下标差来计算以后字符的坐标。
public class Solution { public String convert(String s, int numRows) {if(s.length()<=numRows||numRows==1)return s;StringBuffer stringBuffer = new StringBuffer();int[][] data = new int[numRows][2];for(int i=2;i<numRows;i++){data[i][0]=i-1;data[i][1]=2*numRows-i-1;}int index = 0;while(index<s.length()){stringBuffer.append(s.charAt(index));index += 2*numRows-2;}for(int i=2;i<numRows;i++){while(true){if(data[i][0]>=s.length())break;stringBuffer.append(s.charAt(data[i][0]));data[i][0]+=2*numRows-2;if(data[i][1]>=s.length())break;stringBuffer.append(s.charAt(data[i][1]));data[i][1]+=2*numRows-2;}} index = numRows-1; while(index<s.length()){ stringBuffer.append(s.charAt(index)); index += 2*numRows-2; }return stringBuffer.toString(); }}
0 0
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- Zigzag Conversion
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- ZigZag Conversion
- vim编辑器颜色主题color scheme
- SQL Server中的DBlink的使用
- 《编程导论(Java)·3.2.4 循环语句》
- 《JAVA程序设计》实训第一天——《猜猜看》游戏
- sedna加载xml文件
- ZigZag Conversion
- 推送通知
- C++中不允许定义引用数组
- Oracle 物化视图 初始(一)
- ZOJ 2588 Burning Bridges 割边的求解
- 使用session验证的用户登录界面(简写)
- ArcGIS Server安装配置中的问题总结
- NBA顶薪
- android R.java文件丢失或无法更新