我的leetcode刷题之路就从此时开始,令我没想到的是,我专门挑了一个被标记为easy的开始,但是给我的感觉却是并不easy 费了不少的功夫才搞定他,下面就对此题开始详细说明:
problem: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"
至此,题目叙述完毕,大意就是你输入一个字符串,然后将他用反倒的之字形进行排列,然后一排一排的输出即可。
在最开始,我尝试着去找规律,看每排输出的字符串中的每个在整个字符串的那些地方,然后将其对应输出即可,但是经过半个小时的找规律后,我放弃了,,虽然找着了,但是规律太过于复杂,代码实现太繁琐,进而经过同学提示想到了下面这个方法。
首先先建立三个vector 然后开始先给第一个vector放一个字符,然后 给第二个vector放第二个字符,然后给第三个vector放第三个字符,然后再倒回来给第二个vector放第四个字符…………一直到最后,字符被放完,将这3个vector都给一个string ,最后将string返回。
代码如下:(写的很扯,但是功能基本实现。。。)
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution
{
public:
string convert(string s, int numRows)
{
vector<string> t(numRows);
int size = s.size();
int n = numRows;
bool stop = true;
if (numRows <= 1 || size <= numRows )
{
return s;
}
if (numRows == 2)
{
int i = 0;
while (size > i)
{
if (size > i)
{
t[0] += s[i];
i++;
}
if (size > i)
{
t[1] += s[i];
i++;
}
}
}
if (numRows > 2)
{
int j = 0;
for (int i = 0; i < size; i++)
{
if (j < n && stop == true)
{
t[j] += s[i];
j++;
}
if (j == n)
{
stop = false;
j = n - 2;
continue;
}
if (j >= 0 && stop == false)
{
t[j] += s[i];
j--;
}
if (j == 0)
{
stop = true;
continue;
}
}
}
string s2;
for (int i = 0; i < numRows; i++)
{
s2 = s2 + t[i];
}
return s2;
}
};
int main()
{
string str = "PAYPALISHIRING";
Solution lo;
cout << lo.convert(str, 3);
return 0;
}
结果是: