Easy to understand solution

  • 0

    For a moment ignore the case where there is just one row or where there is more rows than the length of the string.

    Now we can simply make a vector which will be initialized to the number of rows. We can traverse the string and add elements across this vector. When we are at the beginning or end of the vector, we simply change directions.

    When we are done traversing the entire string, we simply concatenate all of the strings in our vector.

    In both of the edge cases, we just return the original string.

    string convert(string s, int numRows) {
    	if (numRows > s.length() || numRows==1) { // handle edge cases
    		return s;
        vector<string> words(numRows);
    	int i = 0;
    	int d = -1;
    	int j = 0;
    	while (i < s.length()) {		
    		words[j] += s[i];
    		d = (j == 0 || j == (numRows - 1)) ? -d : d;
    		j += d;
    	string result="";
    	for (string w : words) {
    		result += w;
    	return result;

Log in to reply

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