leetcode OJ6 ZigZag Conversion 小结

来源:互联网 发布:linux display 详解 编辑:程序博客网 时间:2024/06/06 11:46

ZigZag Conversion

今天把自己吓一跳, leetcode上已经刷到22题了, csdn上才总结了 5 题, 赶紧停下来, 写下总结, 并看看大神的代码。

问题描述

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   NA P L S I I GY   I   RAnd 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 * row, 对于夹在中间的几行, 还有个额外的字符需要处理。
显然, 可以在 O(n)时间复杂度内完成

代码

class Solution {public:    string convert(string s, int numRows) {        if (numRows == 1)            return s;        string result;        for (int cur_row = 0; cur_row != numRows; cur_row++)        {            if (cur_row == 0 || cur_row == numRows - 1)            {                for (int gap = 0; cur_row + gap < s.size(); gap += 2 * (numRows - 1))                    result.push_back(s[cur_row + gap]);                continue;            }            for (int gap = 0; cur_row + gap < s.size(); gap += 2 * (numRows - 1))            {                int gap1 = 2 * (numRows - 1 - cur_row);                if (cur_row + gap < s.size())                    result.push_back(s[cur_row + gap]);                if (cur_row + gap1 + gap < s.size())                    result.push_back(s[cur_row + gap1 + gap]);            }        }        return result;            }};

大神的代码

dem01

思路是一致的, 但是代码明显精简了很多

string convert(string s, int nRows) {        if(nRows <= 1) return s;        string result = "";        //the size of a cycle(period)        int cycle = 2 * nRows - 2;        for(int i = 0; i < nRows; ++i)        {            for(int j = i; j < s.length(); j = j + cycle){               result = result + s[j];               int secondJ = (j - i) + cycle - i;               if(i != 0 && i != nRows-1 && secondJ < s.length())                   result = result + s[secondJ];            }        }        return result;    }
0 0
原创粉丝点击