zoukankan      html  css  js  c++  java
  • leetcode第六题--ZigZag Conversion

    Problem:

    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".

    就是将一个字符串按照“之”字型表示后,按每行组合后输出新字符串。

    在白头翁的博客里学习到了O(n)的算法。

    就是创建nRows个string,将s对应坐标拷贝到每个string中,利用pushback操作。最后append连接输出。代码如下:

    class Solution {  
    public:  
        string convert(string s, int nRows)  
        {      
            if (nRows <= 1 || s.length() < 2)  
                return s;  
      
            string *s_arr = new string[nRows];  
            int nCount = 2 * (nRows - 1);  // 每个循环的轮回 也就是 2倍的nRows - 2
      
            for (int i = 0; i < s.length(); ++i)  
            {  
                s_arr[nRows - 1 -abs(nRows - 1 - (i%nCount))].push_back(s[i]);  
            }  
      
            string str_result;  
            for (int i = 0; i < nRows; ++i)  
                str_result.append(s_arr[i]);  
      
            return str_result;  
        }  
    };

    坐标对应是关键,数学逻辑思维确实要强。可以举个四行的例子试试。

  • 相关阅读:
    linux添加自定义命令
    linux 将自己的服务添加到系统service服务
    制作linux下的.run安装包
    Wowza 相关
    深入理解 Vue Computed 计算属性
    养狗相关知识整理
    柯基犬体重对照图
    window下tomcat的内存溢出问题
    postMan测试https接口
    beego获取用户请求参数的方法
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4019950.html
Copyright © 2011-2022 走看看