c/c++语言开发共享C++中的Z字形变换问题

z字形变换描述将一个给定字符串 s 根据给定的行数 numrows ,以从上往下、从左到右进行 z 字形排列。比如输入字符串为 “paypalishiring” 行数为 3 时

z字形变换

描述

将一个给定字符串 s 根据给定的行数 numrows ,以从上往下、从左到右进行 z 字形排列。

比如输入字符串为 “paypalishiring” 行数为 3 时,排列如下:

p   a   h   n  a p l s i i g  y   i   r  

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“pahnaplsiigyir”。

请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numrows);  

示例1

输入:s = "paypalishiring", numrows = 3
输出:"pahnaplsiigyir"

示例2

输入:s = "paypalishiring", numrows = 4
输出:"pinalsigyahrpi"
解释:
p     i    n
a   l s  i g
y a   h r
p     i

示例3

输入:s = "a", numrows = 1
输出:"a"

思路/解法

模拟法,根据所给条件,线性处理即可(z字形存在一定规律,每当固定的条件后前进方向进行转变)。

class solution {  public:      string convert(string s, int numrows) {          int rows = numrows;  	    int columns = ((s.length() / (2 * rows - 1)) + 1) * rows;//尽可能缩小所使用的空间,这里columns可优化,并未精确求解  	    std::vector<std::vector<char>> arrs(rows, std::vector<char>(columns));    	    //初始化  	    for (int i = 0; i < rows; i++)  		    for (int j = 0; j < columns; j++)  			    arrs[i][j] = '0';    	    int x = 0, y = 0;  	    int index = 0;  	    while (index < s.length())  	    {  		    if (index < s.length() && x < rows)  			    arrs[x++][y] = s[index++];    		    if (index < s.length() && x == rows)  		    {                   //更新x和y  			    y++;  			    x -= 2;  			    while (index < s.length() && x > 0)  				    arrs[x--][y++] = s[index++];  			    x = 0;//重置x  		    }  	    }    	    std::string res;  	    for (int i = 0; i < rows; i++)  	    {  		    for (int j = 0; j < columns; j++)  		    {  			    if (arrs[i][j] != '0' && arrs[i][j] != '')  				    res.push_back(arrs[i][j]);  		    }  	    }  	    return res;      }  };  

到此这篇关于c++中的z字形变换的文章就介绍到这了,更多相关c++ z字形变换内容请搜索<计算机技术网(www.ctvol.com)!!>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<计算机技术网(www.ctvol.com)!!>!

需要了解更多c/c++开发分享C++中的Z字形变换问题,都可以关注C/C++技术分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/1115590.html

(0)
上一篇 2022年7月10日
下一篇 2022年7月10日

精彩推荐