zoukankan      html  css  js  c++  java
  • ZigZag convert

    1 题目

    2   分析

    (1) 对于第一行与最后一行,每两个相邻元素在原字符串中的距离为2*(nRows-1);

    (2) 对于非第一行与最后一行的其他行curRow,若锯齿(zigzag)正往下走。则当前字符与下一个字符在原字符中的距离为2*(nRows-curRow-1);若锯齿正往上走,则当前字符与下一个字符在原字符中的距离为2*curRow。

    3 实现

    string convertex(string s ,int numRows)
    {
    	int size = s.size();
    	if (size <= numRows || numRows <= 1)
    		return s;
    	string res(size, '0');
    	int c = 0;
    	int tempRow = (numRows - 1) * 2;
    
    	//first row
    	for (int i = 0; i < size; i += tempRow)
    	{
    		res[c++] = s[i];
    	}
    
    	//middle
    	for (int curRow = 1; curRow < numRows - 1; ++curRow)
    	{
    		for (int j = curRow; j < size; j += 2 * curRow)
    		{
    			res[c++] = s[j];
    			j += (numRows - curRow - 1) * 2;
    			if (j < size)
    			{
    				res[c++] = s[j];
    			}
    		}
    	}
    
    	//the last row
    	for (int i = numRows - 1; i < size; i += tempRow)
    	{
    		res[c++] = s[i];
    	}
    	return res;
    }


    
    

  • 相关阅读:
    Middleware
    Languages
    Errors
    Config
    CLI Console
    Linux远程复制文件
    CentOS下安装Gitlab
    Maven_POM配置结构
    Maven_POM配置详解
    MySQL索引背后的数据结构及算法原理
  • 原文地址:https://www.cnblogs.com/slgkaifa/p/7400368.html
Copyright © 2011-2022 走看看