【LeetCode】6. ZigZag Conversion

题目链接

https://leetcode.com/problems/zigzag-conversion/

注意点

给定行数可以为1

解法

解法1:找规律。找到每个字符变化前的初始位置与变化后的行数的映射关系。当指定行数为numRows (numRows >1)时,每(numRows -1)*2个连续的字符具有相似的位置关系。如示例2中的LEETCO与DEISHI都成V型分布。通过观察可以发现每个字符处于的层数具有以下规律:

所处层数 = 1 + abs(序号%每组个数 - 给定行数)

同时,对于每一层的字母,原序号越小,则越早输出。

所以可以使用numRows 个字符串储存每层的字符,遍历一遍给定字符串s,依次计算每个字符所处的层数(写一个match函数)并存入对应的字符串中,最后从高到低依次输出各层的字符串,就是题中要求的输出了。

执行用时 :16 ms, 在所有C++提交中击败了74.79%的用户

内存消耗 :8.2 MB, 在所有 C++ 提交中击败了100.00%的用户

int match(int index,int numGroup){
	int row = abs(index%numGroup - (numGroup/2));
	return row;
}

string convert(string s, int numRows) {
    if(numRows == 1) return s; 
	string row[numRows];
    string strRes;
    int numGroup = numRows * 2 - 2;
	for(int i = 0;i < numRows;i++)
	{
		row[i] = "";
	}
	for(int j = 0;j < s.length();j++)
	{
		row[match(j,numGroup)] += s[j];
	}
	while(numRows)
	{
		strRes += row[numRows-1];
		numRows--;
	}
	return strRes;
}

测试代码

#include <stdio.h>
#include <string>
#include <iostream>
#include <cmath>
using namespace std;
int main(){
	string str;	
	int numRows;
	//无限循环测试 
	while(1){
		cin>>str>>numRows;
		cout<<convert(str,numRows)<<endl;
	}
	return 0;
}

遇到问题

1.取绝对值函数:abs(),需引用cmath头文件

小结

找规律,确定字符下标与变换后排列的映射规律即可。

posted @ 2020-05-18 22:45  陳浴巾  阅读(97)  评论(0编辑  收藏  举报