LeetCode 6. ZigZag Conversion 解题报告

本文介绍了一种将字符串以Z字形排列并按行读取的算法实现。通过使用vector容器和标志位来区分字符串的排列方向,最终实现了字符串的有效转换。

题目描述:

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


解题思路:

  本题题意为以z字形格式排列的字符串逐行读出来。由于行数不确定,所以使用vector相对于数组来说更方便一些。使用一个bool变量odd来标记此时字符向下排列(如)还是斜向上方排列。

P   A   H   N
A P L S I I G
Y   I   R              p->A->Y即为odd为真时向下排列 
 向下排列

P   A   H   N
A P L S I I G
Y   I   R              Y->P->A为斜向上排列。但是此时Y和A分别被包含在前两个向下的排列中。P则在odd为假时被加入第二行。
斜向上排列




代码展示

#include <iostream>
#include <string>
#include <vector>
class Solution {
public:
    string convert(string s, int numRows) 
{
        vector<char> tmp;
        vector<vector<char> > res;
        for(int i=0 ; i<numRows ; i++)
        {
            res.push_back(tmp);
        }
        bool flag =false;
        //int jj =0;
        bool odd = true;//odd 标记序列向下移动
        for(int i=0 ; i<s.size()&&!flag;)
        {
            if(odd)
            {
                for(int j=0; j<numRows ;j++)
                {
                    res[j].push_back(s[i]);
                    i++;
                    if(i==s.size())
                    {
                        flag = true;
                        break;
                    }
                
                }
                odd = !odd;
            }
            else
            {
                for(int j=numRows-2; j>0 ;j--)
                {
                    res[j].push_back(s[i]);
                    i++;
                    if(i==s.size())
                    {
                        flag = true;
                        break;
                    }
                
                }
                odd = !odd;
            }
            
        }
        string ans;
        for(int i=0;i<res.size();i++)
        {
            for(int j=0 ; j<res[i].size();j++)
                ans+=res[i][j];
        }
        return ans;
}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值