• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
正在努力成为一个优秀的废物
博客园    首页    新随笔    联系   管理    订阅  订阅
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;
    }
};

 

posted on 2018-02-26 23:30  你算哪根小毛线  阅读(146)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3