My Simple C++ solution


  • 0
    E
    class Solution {
    public:
        string convert(string s, int nRows) {
            if(nRows==1)
            {
                return s;
            }
            
            string result;
            int modnum = nRows*2-2;
            
            for(int i = 0;i<=modnum/2;++i)
            {
                for(int strPos = 0;strPos<s.size();++strPos)
                {
                    if(strPos%modnum==i||strPos%modnum==modnum-i)
                    {
                        result+= s[strPos];
                    }
                }
            }
            return result;
        }
    };

  • 0
    E

    The time complexity of your solution is O(nRows * n), however the best solution is O(n).


  • 0
    J

    My similar solution (more readable):

    class Solution {
    public:
        string convert(string s, int nRows) {
            if (nRows <= 1 || nRows >= s.length()) return s;
            string result = "";
            int maxStep = nRows * 2 - 2;
            for (int i = 1; i <= nRows; i++) {
                int j = i - 1;
                int step = (i < nRows) ? (nRows-i)*2 : maxStep;
                while (j < s.length()) {
                    result += s[j];
                    if (result.length() == s.length()) return result;
                    j += step;
                    if (step < maxStep) {
                        step = maxStep - step;
                    }
                }
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.