• ZigZag Conversion


    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 text, int nRows);

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

    思路:直接模拟就行。一开始想了各种下标的复杂转换,真是没有必要。

    这题还学到了两个知识点:

    1. 想申请一个数组的话,比如string eg[56];这样写的话所申请的数组规模必须预先给定,对于不能确定的数组,申请要动态申请,比如 string *eg = new string[num];

    2. string的append和+运算的区别:append是直接在原字符串的末尾添加,+运算是生成一个新的string来存储运算结果。

     1 class Solution {
     2 public:
     3     string convert(string s, int numRows) {
     4         if (numRows == 1) return s;
     5         string *res = new string[numRows];
     6         int step = 1, row = 0;
     7         for (char c : s)
     8         {
     9             if (row == 0)
    10                 step = 1;
    11             else if (row == numRows - 1)
    12                 step = -1;
    13             res[row] += c;
    14             row += step;
    15         }
    16         string ans;
    17         for (int i = 0; i < numRows; i++)
    18             ans.append(res[i]);
    19         return ans;
    20     }
    21 };
  • 相关阅读:
    [LeetCode] 336. Palindrome Pairs
    [LeetCode] 214. Shortest Palindrome
    [LeetCode] 844. Backspace String Compare
    [LeetCode] 5. Longest Palindromic Substring
    [LeetCode] 269. Alien Dictionary
    [LeetCode] 200. Number of Islands
    [LeetCode] 72. Edit Distance
    [LeetCode] 460. LFU Cache
    [LeetCode] 1229. Meeting Scheduler
    [LeetCode] 22. Generate Parentheses
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4910161.html
Copyright © 2020-2023  润新知