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

    class Solution {
    public:
        string convert(string s, int nRows) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(s=="")return "";
            if(nRows<=1)return s;
            string ret;
            int round=2*nRows-2;//一个V字形有多少个字符 即样例中的P A Y P,全过程就是不断重复这个V字形
            int iter=s.length()/round;//多少格V字形
            int lastStart=iter*round;//最后一个V字形的开始
            //0
            for(int i=0;i<iter;i++){
                ret+=s[i*round];
            }
            if(lastStart<s.length())ret+=s[lastStart];
    		//ret+="
    ";
            for(int j=1;j<nRows-1;j++){
                for(int i=0;i<iter;i++){
                    ret+=s[i*round+j];
                    ret+=s[i*round+j+(nRows-1-j)*2];
                }
                if(lastStart+j<s.length())ret+=s[lastStart+j];
                if(lastStart+j+(nRows-1-j)*2<s.length())ret+=s[lastStart+j+(nRows-1-j)*2];
    			//ret+="
    ";
            }
            //last row
            for(int i=0;i<iter;i++){
                ret+=s[i*round+nRows-1];
            }
            if(lastStart+nRows-1<s.length())ret+=s[lastStart+nRows-1];
    		//cout<<ret<<endl;
            return ret;
        }
    };
    
  • 相关阅读:
    AdminLTE模板
    日历插件
    Jquery 拖拽表格宽度
    Java桌面程序打包成exe可执行文件
    使用Access-Control-Allow-Origin解决跨域
    Ubuntu默认root密码
    Lua的require和module小结
    nginx 安装
    chkconfig命令
    [转]fedora启动telnet服务
  • 原文地址:https://www.cnblogs.com/superzrx/p/3324204.html
Copyright © 2011-2022 走看看