描述
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 s, int numRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
您在真实的面试中是否遇到过这个题?
说明
二三三
样例
Given s = "PAYPALISHIRING"
, numRows = 3
, return "PAHNAPLSIIGYIR"
.
题目的意思是给定一个字符串和行数,把给的字符串按Z字型排列,然后从左到右从上到下输出
比如字符串为:s=abcdefghijklmnopqrst,numRows=4
/*
a g m s
b fh ln rt
c e i k o q
d j p
*/
思路:简单的字符串模拟,可以把生成的Z型字符串算出来,然后逐行输出。
不过我没有选择这个方案,题目的字符串明显是有规律的,按道理是可以把循环节传出来,然后直接取对应下标即可。这样执行效率比较高,没有做什么别的优化,6ms
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<iostream>
using namespace std;
class Solution
{
public:
string convert(string &s,int numRows)
{
if(numRows==1)
return s;
int l=s.length();int i,j;
int recurrent_num=numRows*2-2;
string result;
for(i=1;i<=numRows;++i)
{
if(i==1 || i==numRows)
{
int now_index=i;
while(true)
{
if(now_index>l)
break;
result=result+s[now_index-1];
now_index=now_index+recurrent_num;
}
}
else
{
int now_index1=i;
int now_index2=(recurrent_num-i+2);
while(true)
{
if(now_index1>l)
break;
result=result+s[now_index1-1];
now_index1=now_index1+recurrent_num;
if(now_index2>l)
break;
result=result+s[now_index2-1];
now_index2=now_index2+recurrent_num;
}
}
}
return result;
}
};
int main()
{
Solution solve;
string s="Apalindromeisaword,phrase,number,orothersequenceofunitsthatcanbereadthesamewayineitherdirection,withgeneralallowancesforadjustmentstopunctuationandworddividers.";
cout<<solve.convert(s,2)<<endl;
system("pause");
return 0;
}