C++:Z 字形變換

 將一個給定字符串根據給定的行數,以從上往下、從左到右進行 Z 字形排列。

比如輸入字符串爲 "LEETCODEISHIRING" 行數爲 3 時,排列如下:

L   C   I   R
E T O E S I I G
E   D   H   N
之後,你的輸出需要從左往右逐行讀取,產生出一個新的字符串,比如:"LCIRETOESIIGEDHN"。

請你實現這個將字符串進行指定行數變換的函數:

string convert(string s, int numRows);
示例 1:

輸入: s = "LEETCODEISHIRING", numRows = 3
輸出: "LCIRETOESIIGEDHN"
示例 2:

輸入: s = "LEETCODEISHIRING", numRows = 4
輸出: "LDREOEIIECIHNTSG"
解釋:

L     D     R
E   O E   I I
E C   I H   N
T     S     G

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/zigzag-conversion
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

class Solution {
public:
    string convert(string s, int numRows) {
        int row = 0;
        int index = 0;
        bool stream_direction = 0; //down
        vector<char> *vector_arr;
        vector_arr = new vector<char>[numRows];
        string s_ret;

        if(numRows == 1)
        {
            s_ret = s;
            return s_ret;
        }

        while(index < s.size())
        {
            vector_arr[row].push_back(s[index]);

            if((row == (numRows - 1)) && (stream_direction == 0))
            {
                stream_direction = 1;  //up
            }

            if((row == 0) && (stream_direction == 1))
            {
                stream_direction = 0;  //down
            }

            if(stream_direction == 0)
            {
                row++;
            }

            if(stream_direction == 1)
            {
                row--;
            }

            index++;
        }

        for(row = 0; row < numRows; row++)
        {
            if(vector_arr[row].size() > 0)
            {
                s_ret.append(&vector_arr[row][0], vector_arr[row].size());
            }
        }
        
        return s_ret;
    }
};

 

發佈了167 篇原創文章 · 獲贊 60 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章