[LeetCode]6. ZigZag Conversion

原题链接:https://leetcode.com/problems/zigzag-conversion/description/

意思是给定输入字符串和行数,把字符串字符按照锯齿状排列后,按行从左到右输出目标字符串。

我的实现:

class Solution {
public:
    string convert(string s, int numRows) {
        if (s.length() == 0)
            return "";
        
        vector<vector<char>> storage(numRows);
        int count = 0, rowIndex = 0;
        bool direction = true;
        
        while (count < s.length()) {
            storage[rowIndex].push_back(s[count]);
            
            if (numRows > 1) {
                if (rowIndex >= numRows - 1 || rowIndex <= 0)
                    direction = !direction;

                if (!direction)
                    rowIndex++;
                else
                    rowIndex--;
            }
            
            count++;
        }
        
        string result = "";
        
        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j < storage[i].size(); j++) {
                result = result + storage[i][j];
            }
        }
        
        return result;
    }
};

解释:zigzag排列字符是有规律的,我是以从顶点直线向下开始到达最下端,然后又斜向上直到最上端为一个周期,每一步向下行数+1, 向上行数-1,实现时注意触底和触顶的处理(错了好多次)。按行存字符,最后按行输出就行。

总结:字符串处理,边界条件判断,找规律

原文地址:https://www.cnblogs.com/qianzixuan1996/p/8288372.html