Description
will be given a string based on the number given row, to down, left to right from the Z-shaped arrangement.
Example, the input string is the number of rows "LEETCODEISHIRING" is 3, arranged as follows:
LCIR
ETOESIIG
EDHN
After that, you need the output from left to right read line by line, produce a new string, such as: "LCIRETOESIIGEDHN".
Examples of
ideas
- Method 1 (I do) the string into n lines, each obtained his string, and then stitching (Because it involves a variety of computing, it is not recommended)
- Method 2
[numRows empty string] traversal s, in turn spliced to a character string of a string array (arr [index]) in, index change: from 0 to numRows, and from 0 to numRows, and so forth, Z-shaped Well
the answer
- python
*方法1*
def convert(self, s: str, n: int) -> str:
if n==1: return s
ss = ''
for r in range(1,n+1):
if r==1 or r==n:
j=r-1
while j<len(s):
ss += s[j]
j+=(2*n-3+1) #n==1时不行
else:
j=r-1
count=1
while j<len(s):
ss += s[j]
if count%2==1:
j += 1+(n-1-r)*2+1
else:
j += 1+(r-2)*2+1
count+=1
return ss
*方法2*
def convert(self, s: str, numRows: int) -> str:
if numRows==1:return s
res=['']*numRows
index = 0
flag=1
for c in s:
res[index]+=c
if index==numRows-1: flag=-1
if index==0: flag=1
index+=flag
return ''.join(res)
- c++
*方法1*
string convert(string s, int n) {
if (n==1) return s;
string ss("");
for (int r=1; r<=n; r++)
{
if (r==1 || r==n)
{
int j=r-1;
while (j<s.size())
{
ss += s[j];
j+=2*n-3+1;
}
}
else
{
int j=r-1,count=1;
while (j<s.size())
{
ss+=s[j];
if (count%2==1)
j+=1+(n-1-r)*2+1;
else
j+=1+(r-2)*2+1;
count++;
}
}
}
return ss;
}
*方法2*
string convert(string s, int numRows) {
if (numRows==1) return s;
vector<string> v(numRows, "");
int index=0,flag=1;
for (char c: s)
{
v[index].push_back(c);
if (index==numRows-1) flag=-1;
if (index==0) flag=1;
index+=flag;
/*
if (flag==1) index++;
if (flag==-1) index--;
*/
}
string res("");
for (auto t: v)
res+=t;
return res;
}