刷题笔记

【leetcode刷题笔记】006.ZigZag Convers

2018-09-13  本文已影响0人  常恒毅
日期:20180912
题目描述:

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   N
A P L S I I G
Y   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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I
详解:

这个题没有什么可说的,大二C语言练习题的难度,看了速度最快的方法也是这么循环,速度在一个数量级上,毕竟输出一个长度为n的字符串最低的复杂度也就是O(n)了。

class Solution {
public:
    string convert(string s, int numRows) {
        int len = s.size();
        int n = numRows;
        string res;
        if(numRows==1){ //n为1的时候的特殊情况,照原样输出。
            return s;
        }
        for(int i=0;i<len;i+=(2*n-2)){//第一行
            res += s[i];
        }
        for(int j=1;j<n-1;j++){//从第2行输出到第n-1行
            for(int i=j;i<len;i+=(2*n-2)){
                res += s[i];
                if((i+2*n-2*j-2)<len){
                    res += s[i+2*n-2*j-2];
                }
            }
        }
        for(int i=n-1;i<len;i+=(2*n-2)){//最后一行
            res += s[i];
        }
        return res;
    }
};

顺便一提的是,C++中的string类,可用str.size()方法获取长度。往一个字符串的末尾添加元素时,直接加就好,这是因为C++中的string类重载了“+”运算符。str.end()指向的末尾元素的后面,也就是'\0'。

上一篇下一篇

猜你喜欢

热点阅读