leetcode 6 ZigZag Conversion

我的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;
}

结果是:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值