8_leetcode_ZigZag Conversion

来源:互联网 发布:隐藏域名ip cdn 编辑:程序博客网 时间:2024/06/08 12:39

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   NA P L S I I GY   I   R
And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR"

//1:当nRows不大于1的时候,直接返回原来字符串;2:考虑i == 0 和i == nRows - 1两种情况; 3:当i介于两者之间的时候氛围两种情况:k += 2 * (nRows - 1 - i) 以及 k += 2 * i

    string convert(string s, int nRows)    {        if(nRows <= 1)            return s;                string result = "";        int length = (int)s.size();                for(int i = 0; i < nRows; i++)        {            if(i == 0 || i == nRows - 1)            {                int k = i;                while( k < length)                {                    result.push_back(s[k]);                    k += 2 * (nRows - 1);                }            }            else            {                int k = i;                bool flag = false;                while(k < length)                {                    result.push_back(s[k]);                                                if(flag == false)                    {                        k += 2 *(nRows - 1 - i);                        flag = true;                    }                    else                    {                        k += 2 * i;                        flag = false;                    }                }            }        }                        return result;    }


0 0
原创粉丝点击