zoukankan      html  css  js  c++  java
  • 64. ZigZag Conversion

    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: 刚开始正着方三个,然后反着放两个,正着放两个。直到结束。(优)

    class Solution {
    public:
        string convert(string s, int nRows) {
            if(nRows <= 1 || s == "") return s;
            int len = s.length();
    		string s2[nRows];
            int k = 0, k2 = 0;
            while(k2 < len){
                while(k < nRows && k2 < len) s2[k++].push_back(s[k2++]);
    			k--;
                while(k > 0 && k2 < len) s2[--k].push_back(s[k2++]);
    			k++;
            }
            string s3;
            for(int i = 0; i < nRows; ++i) {
                s3 += s2[i];
            }
            return s3;
        }
    };
    

     方法二: 类似方法一,不过存下每个位置的字符应该放的地方。然后依次读入。

    class Solution {
    public:
        string convert(string s, int nRows) {
            if(nRows <= 1 || s == "") return s;
            int len = s.length();
    		vector<int> index(2*nRows-2);
    		int t = 0;
    		for(int i = 0; i < nRows; ++i) index[t++] = i;
    		for(int j = nRows-2; j > 0; --j) index[t++] = j;
    		string s2[nRows];
            int k = 0, m = 2*(nRows-1);  
            while(k < len){
    			s2[index[k % m]].push_back(s[k]);
    			k++;
            }
            string s3;
            for(int i = 0; i < nRows; ++i) {
                s3 += s2[i];
            }
            return s3;
        }
    };
    
  • 相关阅读:
    C#ModBus Tcp 报文解析
    C#ModBus Tcp的学习及Master的实现
    C#原生Socket服务器与客户端的实现
    转载:C# 创建、部署和调用WebService的简单示例
    记kepServer读写西门子PLC
    C#实现某一属性值变化时触发事件
    C#倒计时关闭提示框
    C#SuperSocket的搭建--通过配置启动
    C#串口扫描枪的简单实现
    C#SuperSocket服务器的简易实现
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3961253.html
Copyright © 2011-2022 走看看