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

    这个题目只要找到每一行字符串间隔的规律就行了,第一行和最后一行间隔 2 * (numRows - 1),中间行每次插入两个他们之间间隔2 * (numRows-i)

    class Solution {
    public:
        string convert(string s, int numRows) {
            if (numRows <= 1)return s;
            string ret;
            for (int i = 1;i <= numRows;++i)
            {
                for (int j = i-1;j < s.size();j += 2 * (numRows - 1))
                {
                    if (1 == i || numRows == i)
                    {
                        ret.push_back(s[j]);
                    }
                    else
                    {
                        ret.push_back(s[j]);
                        if(j+2 * (numRows-i)<s.size())
                        ret.push_back(s[j + 2 * (numRows-i)]);
                        else break;
                    }
                }
            }
            return ret;
        }
    };
  • 相关阅读:
    hdu 1518 square
    AWR报告的使用
    状态模式之观察者和状态模式
    Arduino笔记五三轴陀螺仪L3G4200D
    TCP IP 学习笔记 二 链路层
    机房收费系统数据库设计小结
    TMSSCRIPTER介绍
    TMSScripter语法
    listview的一些用法
    进制转换
  • 原文地址:https://www.cnblogs.com/csudanli/p/5890484.html
Copyright © 2011-2022 走看看