LeetCode(6)

来源:互联网 发布:售楼软件哪家好 编辑:程序博客网 时间:2024/06/04 01:28

Description :

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this:题目描述
“PAYPALISHIRING” 这个单词被用(之字形)写成了如上图所示 . 我们要实现一个函数 convert(string s, int nRows) 将字符串 s 变成像上图那样的 nRows 行(之字形) , 然后按行把它读出来 . 如图 按行读出来就是 : PAHN-APLSIIG-YIR

string convert(string s, int nRows) {    if (nRows <= 1)  return s;    const int len = (int)s.length();    //创建了一个二维数组,str[row] 保存了每一行的字符串 .    string *str = new string[nRows];    int row = 0, step = 1;    for (int i = 0; i < len; ++i){        str[row].push_back(s[i]);        if (row == 0)            step = 1;        else if (row == nRows - 1)            step = -1;        row += step;    }    s.clear();    for (int j = 0; j < nRows; ++j)    {        s.append(str[j]);    }    delete[] str;    return s;}
原创粉丝点击