zoukankan      html  css  js  c++  java
  • 【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头文件

    小结

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

  • 相关阅读:
    用fnmatch函数进行字符通配
    activity和service之间的相互通信方法
    IGMP协议简介
    Android2.2快速入门
    Android开发之旅:HelloWorld项目的目录结构
    Android的五大基本组件
    Android Service 组件
    TCP交互数据流 成块数据流
    为什么要进行IP选路?
    embOS实时操作系统 任务通讯
  • 原文地址:https://www.cnblogs.com/ChenYujin/p/12913536.html
Copyright © 2011-2022 走看看