lintcode 1363. 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 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;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值