leetcode第六题z字型对比自己算法和大佬算法

大佬的答案

class Solution {
public:
	string convert(string s, int numRows) {

		if (numRows == 1) return s;

		vector<string> rows(min(numRows, int(s.size()))); // 防止s的长度小于行数
		int curRow = 0;
		bool goingDown = false;

		for (char c : s) {
			rows[curRow] += c;
			if (curRow == 0 || curRow == numRows - 1) {// 当前行curRow为0或numRows -1时,箭头发生反向转折
				goingDown = !goingDown;
			}
			curRow += goingDown ? 1 : -1;
		}

		string ret;
		for (string row : rows) {// 从上到下遍历行
			ret += row;
		}

		return ret;
	}
};

总结:
1.关于string,string重载了[]所以string的每一个元素视为char类型,所以在使用范围for循环中使用了char:而不是string
2.算法的第一个循环关键点是goingdown这个标志位,最开始是0,之后通过if语句置为1,开始向下进行移动。
直至出现了numrows-1的情况开始沿对角线移动,在算法中直接将对角线的值往每一行的后边添加,这是因为题目的要求是从左至右读出,就不用去建立数组了。
自己的代码:(及其复杂,堪称灾难,还用数组思想)

class Solution {
public:
    string convert(string s, int numRows) {
        string result_zs;
        string a;
        
        int len=s.size();
        if( len<2)
            return s;
        else if(numRows==1) return s;
        else
        {
        int row =numRows;
        size_t col = (len / (2 * numRows - 2)) * (numRows - 1);
        if ((((len % (2 * numRows - 2)) / numRows) == 1) && ((len % (2 * numRows - 2)) % numRows) == 0)
        col = col + 1;
        else if ((((len % (2 * numRows - 2)) / numRows) == 1) && ((len % (2 * numRows - 2)) % numRows) != 0)
        col = col + 1 + ((len % (2 * numRows - 2)) % numRows);
        else if ((((len % (2 * numRows - 2)) / numRows) == 0) && ((len % (2 * numRows - 2)) % numRows) != 0)
        col = col + 1;
        else if ((((len % (2 * numRows - 2)) / numRows) == 0) && ((len % (2 * numRows - 2)) % numRows) == 0)
        col = col;
        auto iter=s.begin();
        string z_s[row][col];
        for(int j=0;j<col;j++)
        {
            if(j%(numRows-1)==0)
            {  
                for(int i=0;i<row&& iter < s.end();i++)
                {
                    z_s[i][j]=*iter;
                    iter++;
                }
            }
            else
            {
                for(int i=0;i<row&& iter < s.end();i++)
                {
                    if((i+j)%(numRows-1)==0)
                    {
                      z_s[i][j]=*iter;
                      break;
                    }
                }
                iter++;
            }
            
        }
        for (int i = 0; i < row; i++)
        {
        for (int j = 0; j < col; j++)
            if (z_s[i][j] != a)
            {
                result_zs += z_s[i][j];
            }
        }
        return result_zs;
    }
    }
};```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值