ZigZag Conversion(leetcode)

本文介绍了一种将字符串以ZigZag形式分布并重新读取的算法实现。通过构造稀疏矩阵来存储每个字符的位置信息,并最终按行顺序重组字符串。提供了完整的代码示例及解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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".

解题思路:

ZigZag折线

  1. 如果nRows = 1时,convert返回:
    PAYPALISHIRING
  2. 如果nRows=2时,convert返回:
    PYAIHRN
    APLSIIG
  3. 如果nRows=4时,convert返回:
    P  I  N
    A LS IG
    YA HR  
    P  I   
    使用稀疏矩阵的方法可以存储每个字符。返回时按行装入string类容
    #include <iostream>
    #include <string>
    #include <list>
    using namespace std;
    
    class Solution {
    public:
    	string convert(string s, int nRows) {
    		ELE *p = new ELE[s.size()];
    		int flag = 1;
    		string res;
    		int temp = 0;
    		
    		for (int i = 0; i < s.size() && nRows != 1;)
    		{
    			if (flag)
    			{
    				while (temp < nRows && i < s.size())
    				{
    					p[i].ele = s[i];
    					p[i].row = temp++;
    					i++;
    				}
    				flag = (flag + 1) % 2;
    			}
    			else
    			{
    				temp -= 2;
    				while (temp > 0 && i < s.size())
    				{
    					p[i].ele = s[i];
    					p[i].row = temp--;
    					i++;
    				}
    				flag = (flag + 1) % 2;
    			}
    		}
                    /* 这部分代码可以优化,创建nRows个List, 每个List存放数组中的行,那么装入string类容器时只需要遍历s.size(), 
  4.                 整个程序的算法复杂就会降为O(s的长度) */
    		int k = 0;
    		for (int i = 0; i < nRows && nRows != 1; i++) //每行一次入容器
    		{
    			for (int j = 0; j < s.size(); j++)//将第i行入容器
    			{
    				if (p[j].row == i)
    					res += p[j].ele;
    					//cout << p[j].ele;
    			}
    		}
    		if (nRows == 1)
    			res = s;
    		return res;
    	}
    
    private:
    	typedef struct //稀疏矩阵方法
    	{
    		char ele;
    		int row;
    		//        int col;
    	} ELE;
    };
    
    int main()
    {
    	class Solution s;
    	string ttt("PAYPALISHIRING");
    	string ans;
    	ans = s.convert(ttt, 3);
    	cout << ans << endl;
    	return 0;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值