leetcode: ZigZag Conversion

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".

思路

很简单,算好什么时候输出哪个就行了。关键的是!!!注意边界情况,不然会导致你的程序在测试的时候出现意料之外的错误。下面是两个版本的程序,一个使用的是char数组作为结果缓存,一个使用的是高端大气的stringstream。
class Solution {
public:
    string convert(string s, int nRows) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.    
		if(nRows==1) return s;
		int oneUnit=2*nRows-2;
		char* rstr=new char[s.length()+1];
		int pt=0;
		for(int i=0;i<s.length();i+=oneUnit)
		{
			rstr[pt++]=s[i];
		}
		for(int j=1;j<nRows-1;j++)
		{
			for(int i=0;i<s.length();i+=oneUnit)
			{
				if(i+j<s.length())
					rstr[pt++]=s[i+j];
				if(i+2*nRows-2-j<s.length())
					rstr[pt++]=s[i+2*nRows-2-j];
			}
		}
		for(int i=nRows-1;i<s.length();i+=oneUnit)
		{
			rstr[pt++]=s[i];
		}
		rstr[pt++]='\0';
		string res(rstr);
		delete rstr;
		return res;
    }
};

class Solution {
public:
    string convert(string s, int nRows) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.    
		if(nRows==1) return s;
		int oneUnit=2*nRows-2;
		stringstream stream;
		for(int i=0;i<s.length();i+=oneUnit)
		{
			stream<<s[i];
		}
		for(int j=1;j<nRows-1;j++)
		{
			for(int i=0;i<s.length();i+=oneUnit)
			{
				if(i+j<s.length())
					stream<<s[i+j];
				if(i+2*nRows-2-j<s.length())
					stream<<s[i+2*nRows-2-j];
			}
		}
		for(int i=nRows-1;i<s.length();i+=oneUnit)
		{
			stream<<s[i];
		}
		string res;
		stream>>res;
		stream.str("");
		stream.clear();
		return res;
    }
};

前面stringstream版本提交的几次Memory Limit Exceeded都是因为没有处理nRows=1的情况,导致第一个循环中一直向stream中写数据,直至超出内存限制。后面char数组版本提交一次Runtime Error也是因为上面的边界情况没有处理,导致数组越界,两次Wrong Answer是因为根据char数组生成string的数组貌似必须最后一位是'/0',不然会出些莫名其妙的问题(在我自己的电脑上就没有问题)。这几个问题长记性了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值