24 ms C++ solution, easy to understand


  • 0

    The example is not quite well for it had not made a clear definition of 'Zigzag'.
    When come to the case "abcdef", 4. The string should be converted into

    a
    b f
    c e
    d
    

    which should return "abfced" rather than "abecfd".

    string convert(string s, int n) 
    {
    	if (n < 2)
    		return s;
    	vector<string> v(n, "");
    	int i, j, odd = 1;
    	int sz = s.size();
    	for (i = 0; i < sz;)
    	{
    		for (j = 0; j < n && i < sz; ++i, ++j)
    			v[j].push_back(s[i]);
    		for (j = n - 2; j && i < sz; ++i, --j)
    			v[j].push_back(s[i]);
    	}
    	string ret = v[0];
    	for (i = 1; i < n; ++i)
    		ret += v[i];
    	return ret;
    }

Log in to reply
 

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