C++ leetcode::ZigZag Conversion

mmp,写完没保存,又得重新写。晚上写了简历,感觉身体被掏空,大学两年半所经历的事,一张A4纸都写不满,真是一事无成呢。这操蛋的生活到底想对我这个小猫咪做什么。

今后要做一个早起的好宝宝~晚起就诅咒自己期末考试考的不会、会的不考。

题目:

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"

题目一看并不难,通过下标来决定该位置的字母应该放在哪里,在此就不赘述公示了,纸上推一推就出来了。不过写这个题的时候自己犯了一个大错误,就是嵌套循环中更新了遍历字符串的下标变量,但是循环终止条件没有考虑越界。这也是我经常犯的一个错误,下次不能再犯了,不然一点长进都没有。

class Solution {
public:
    string convert(string s, int numRows) {
        string result[numRows];
        int sum=2*numRows - 2;
        int i = numRows;
        if (s.size()<=numRows || numRows == 1)
            return s;
        for(int j = 0; j < numRows&&j<s.size(); j++){
            result[j] = s[j]; 
        } 
        while(i<s.size()){
            int k = 0;
            while(k<numRows -2 && i<s.size())
            {
                if(i%sum == numRows+k && i%sum != sum)
                    result[numRows-2-k] =  result[numRows-2-k] + s[i];
                i++;
                k++;
               
            }
            for(int j = 0; j < numRows && i < s.size(); j++){ 
                result[j] = result[j] + s[i];
                i++;
            } 
        }
        string conversion;
        for(int j = 0; j < numRows && j < s.size(); j++)
                conversion = conversion + result[j];
        return conversion;
    }
};

  

提交代码后,42ms,击败15%。我想不出更好的解法了。看看大佬的,mmp,也没看懂。

class Solution {
public:
    string convert(string s, int numRows) 
    {
        vector<string> substring(numRows);
        int l = s.length();
        int counter = 0;
        
        if(numRows == 1)
            return s;
        
            int i = 0; 
        while (i < numRows)
        {
            if (counter == l)
                break;
            
            substring[i] += s[counter];
            counter++;
            
            if (i == (numRows-1) && counter != l)
            {
                for(int j = i - 1; j>=0;j--)
                {
                    if (counter == l)
                    break;
                    
                    substring[j] += s[counter];
                    counter++;  
                }
                 i=0;
            }   
            ++i;
        } 
        

        
        string result ;

         for(int k = 0; k<numRows; k++)
        {
             result += substring[k];
        }
        return result;
    }
};

 

转载于:https://www.cnblogs.com/catpainter/p/8476676.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值