zigzag-conversation

【题目描述】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".

【解题思路】希望在一次迭代中完成对字符串的分组。而经过简单的分析,可以发现迭代的索引与分组的索引有非常规律的对应关系。
对(nRows-1)取余,可以区分行数。
对(nRows-1)做除,可以区分当前是上升还是下降(偶数上升,奇数下降)。
根据余数和整数就可以确定每一个字符所在的行数。

【考查内容】字符串

class Solution {
public:
    string convert(string s, int numRows) {
		// 判断行数是否大于1,字符串是否存在,否则直接输出
		if (s.size() == 0 || numRows < 2)
			return s;
 
		// 创建字符串数组,用于存储每一行的字符串
		vector<string> ret(numRows);
 
		// 一次遍历
		for (size_t i = 0; i < s.size(); i++){	
			// 利用numRows-1取余和取整
			int m = i % (numRows - 1);
			int n = i / (numRows - 1);
 
			// 利用余数和整数判断当前字符在第几行,然后就存入相应行数的字符串中
			(n & 0x1 ? ret[numRows - 1 - m] : ret[m]).push_back(s[i]);
 
		}
 
		// 将各个字符串按照行顺序进行叠加,得到最重要输出的字符串
		return accumulate(ret.begin(), ret.end(), string());
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值