首页 > 代码库 > LeetCode ZigZag Conversion
LeetCode ZigZag Conversion
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 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"
.
题目描述:
按照之字格式输入数据,并且按照横向输出。
如图。
解题思路:
设n为输入行数,i为行号
观察图像寻找规律。
如果是第0行和最后一行每个字符之间的距离为2*n-2
如果是中间行,若该行列号为偶数则与下个字符距离2*(n-i-1) ,否则若为奇数则与下个字符相距离2*i
例如:
图中所示,第1行,第一个字符为1,列号为0,为偶数,则与第二个距离为2*(5-1-1)=6
即下个字符为6+1=7
由于7的字符列号为3为奇数,所以下个字符的列号距离为2*1=2 即7+2=9
public class Solution { public String convert(String s, int nRows) { String res=""; int len=s.length(); if (nRows <= 1 || len == 0 ||len<nRows) //判断行数及字符长度是否不符合 return s; for(int i=0;i<nRows;i++) { int index = i; res +=s.charAt(index); boolean flag = true;//偶数 for(int k=0;index<len;k++) { if(i==0||i==nRows-1) //使用公式1 { index +=2*nRows - 2; } else{ //中间数字使用公式2 if(flag) //偶数 { index+=2*(nRows-1-i); flag = false; } else{ index+=2*i; flag =true; } } if(index<len)//判断是否超出界限,若不超出则加入 res+=s.charAt(index); } } return res; } }
LeetCode ZigZag Conversion
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。