https://leetcode-cn.com/problems/zigzag-conversion/
难度中等1237
将一个给定字符串 s
根据给定的行数 numRows
,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "PAYPALISHIRING"
行数为 3
时,排列如下:
P A H N A P L S I I G Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"
。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入:s = "PAYPALISHIRING", numRows = 3 输出:"PAHNAPLSIIGYIR"
示例 2:
输入:s = "PAYPALISHIRING", numRows = 4 输出:"PINALSIGYAHRPI" 解释: P I N A L S I G Y A H R P I
示例 3:
输入:s = "A", numRows = 1 输出:"A"
class Solution {
public String convert(String s, int numRows)
{
int n =0;
String ans="";
int n_ = numRows*2-2;
int m = numRows*2-2;
int flag = 0;
if(numRows == 1 ) return s;
while(n<numRows)
{
for(int i = n;i<s.length();)
{
// System.out.print(" i="+i);
ans+=""+s.charAt(i);
if(n== 0 || n==numRows-1)
{
i+=m;
if(i == 0 ) return ans;
}
else
{
if(flag == 0 ){
i+=n_;
flag = 1;
}
else{
i+=m-n_;
flag =0;
}
}
}
n++;
n_-=2;
if(n==0 || n == numRows-1) n_=numRows*2-2;
flag =0;
}
return ans;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69237.html