leetcode 006 Z 子型变换 - medium

1 题目 : Z 子型变换

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:

P A H N
A P L S I I G
Y I R

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。

请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

示例 1:

输入:s = “PAYPALISHIRING”, numRows = 3
输出:“PAHNAPLSIIGYIR”

示例 2:

输入:s = “PAYPALISHIRING”, numRows = 4
输出:“PINALSIGYAHRPI”
解释:
P I N
A L S I G
Y A H R
P I

示例 3:

输入:s = “A”, numRows = 1
输出:“A”

提示:

1 <= s.length <= 1000
s 由英文字母(小写和大写)、‘,’ 和 ‘.’ 组成
1 <= numRows <= 1000

2 直接模拟法

直接按照题目描述将每个字母填入到二维表格相应的位置上,缺点是时间复杂度和空间复杂度都是 O ( N 2 ) O(N^2) O(N2).

代码

string convert(string s, int numRows) {
    if(numRows == 1) return s;
    vector<vector<char> > mat(numRows, vector<char>(s.size(), 0));
    int dr[] = {1, -1};
    int dc[] = {0, 1};
    int r = 0, c = 0, d = 0;
    for(int i = 0; i < s.length(); i++){
        mat[r][c] = s[i];
        r += dr[d];
        c += dc[d];
        if(r == 0 || r == numRows - 1)
            d = (d + 1) % 2;
    }

    string result;
    for(int i = 0; i < numRows; i++){
        for(int j = 0; j < s.size(); j++){
            if(mat[i][j])
                result.push_back(mat[i][j]);
        }
    }

    return result;
}

结果

leetcode 006 Z 子型变换 - medium_第1张图片

3 数学法

直接找到每一行的字符在原字符串中的位置。时间复杂度 O ( N ) O(N) O(N)。空间复杂度 O ( N ) O(N) O(N)

代码

string convert(string s, int numRows) {
    if(numRows == 1) return s;
    int n = s.size();
    string result;
    for(int i = 0; i < numRows; i++){
        for(int j = i; j < n ; j += 2 * numRows - 2){
            result.push_back(s[j]);
            if(i != 0 && i != numRows - 1 && j + 2 * numRows - 2 - 2 * i < n){
                result.push_back(s[j + 2 * numRows - 2 - 2 * i]);
            }
        }
    }

    return result;
}

结果

leetcode 006 Z 子型变换 - medium_第2张图片

你可能感兴趣的:(Leetcode,leetcode,算法,c++)