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) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.    
    		int len=s.length();
    		string s1(len,'a');
    		int gap=2*nRows-2;
    		int i,j,k;
    	    i=0;//s1下标
    		j=0;//行
    		int index=0;//对应s下标
    		if(nRows==1) return s;
    		while(i<len)
    		{
    			index=j;		
    			if(j==0||j==(nRows-1))
    			{				
    				while(index<len)
    				{
    					s1[i]=s[index];
    					index+=gap;					
    					i++;
    				}
    			}
    			else
    			{
    				s1[i]=s[index];			
    				while(index<len) /*内部也要判断*/
    				{
    					i++;
    					index+=gap-2*j;
    					if(index>=len) break;	
    					s1[i]=s[index];
    					i++;
    					index+=2*j;
    					if(index>=len) break;	
    					s1[i]=s[index];
    				}			
    			}
    			j++;
    		}
    		return s1;
        }
    };
    

          当不满足while条件时,还要运行完while语句才会跳出循环。在此mark,祭奠我像傻子一样的一个小时。

  • 相关阅读:
    nginx
    vue拦截
    时间转化封装
    Vue粒子特效(vue-particles插件)
    vscode 使用ESLint 自动检查,保存时自动格式化
    小程序请求封装
    common.js
    h5常见
    封装promise
    promise使用
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3411636.html
Copyright © 2011-2022 走看看