zoukankan      html  css  js  c++  java
  • 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"

    Subscribe to see which companies asked this question

    这种找规律的问题应该比较适合使用归纳法进行处理,不过光用肉眼看也能看出点规律。

    设i 为行号,从1开始。numRows为行数

    则1到7 是(1 + 2 * numRows - 2)

    2到8 是(2 + 2 * numRows - 2)

    2到6是(2 + 2 * numRows - 2) - 2

    3到9是(3+ 2 * numRows - 2)

    3到5是(3+ 2 * numRows - 2) - 2 * 2

    注意行数为1的时候应该是返回本身

    class Solution {
    public:
        /*
         * 找规律
         * 1    7
         * 2  6 8
         * 3 5  9
         * 4    10
         *
         */
        string convert(string s, int numRows) {
                int len_s = s.length();
                if (1 == numRows) {
                    return s;
                }
                string res = "";
              
                int i;
                for (i=0; i<numRows; i++) {
                    int index = i;
                    while (index < s.length()) {
                        res += s[index];
                        if (1 <= i && i<(numRows-1)) {
                            if ((index + 2 * numRows - 2 - 2 * i) < s.length()) {
                                //cout << (index + 2 * numRows - 2 - 2 * i) << endl;
                                res += s[index + 2 * numRows - 2 - 2 * i];
                            } else {
                                break;
                            }
                        }
                        index = (index + 2 * numRows - 2);
                    }
                }
            return res;
        }
    };
  • 相关阅读:
    定位 frame 中的对象
    层级定位
    定位一组对象find_elements
    设置等待时间
    selenium python的使用(一)
    selenium python 安装
    Linux 用户管理(2)
    Linux 用户管理(1) (/etc/passwd)
    U盘在电脑上安装CentOS 7 系统过程详解
    vi编辑文件保存后,提示“Can't open file for writing Press ENTER or type command to continue”
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5095257.html
Copyright © 2011-2022 走看看