1. 程式人生 > 其它 >Leetcode 6 Z字形變換

Leetcode 6 Z字形變換

技術標籤:Leetcode每日打卡_每日一道leetcode演算法資料結構

Leetcode 6 Z字形變換

題目描述

將一個給定字串 s 根據給定的行數 numRows ,以從上往下、從左到右進行 Z 字形排列。

比如輸入字串為 “PAYPALISHIRING” 行數為 3 時,排列如下:

示例圖片

之後,你的輸出需要從左往右逐行讀取,產生出一個新的字串,比如:“PAHNAPLSIIGYIR”。

請你實現這個將字串進行指定行數變換的函式:

string convert(string s, int numRows);

來源:力扣(LeetCode)題目連結
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

題解1

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows == 1) return s;
        unordered_map<int, string> hash;
        int len = s.length();
        string finals = "";
        int p = (numRows -
1) << 1; for(int i = 0; i < len; i++){ int r = i % p; if(r < numRows){ hash[r] += s[i]; }else{ //找找關係即可 hash[(p-r)] += s[i]; } } for(int i = 0; i < numRows; i++){ finals +
= hash[i]; } return finals; } };

提交結果

題解2(只用了個min,提高了點速度)

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows == 1) return s;
        unordered_map<int, string> hash;
        int len = s.length();
        string finals = "";
        int p = (numRows - 1) << 1;
        for(int i = 0; i < len; i++){
            int r = i % p;
            //和題解1比較,其實我們需要選的是r和p-r中小的那個
            hash[min(r,p-r)] += s[i];
        }
        for(int i = 0; i < numRows; i++){
            finals += hash[i];
        }
        return finals;
    }
};

提交結果

題解3(按行讀)

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows == 1) return s;
        int len = s.length();
        string finals = "";
        int p = (numRows - 1) << 1;
        for(int i = 0; i < numRows; i++){
           for(int j = 0; j+i < len; j+=p){
               finals += s[i+j];
               //可以找規律,發現不規則的之間差了 p-i
               if(i != 0 && i != numRows-1 && j+p-i < len)
                    finals += s[j+p-i];
           }
        }
       
        return finals;
    }
};

提交結果