6. ZigZag Conversion\38. Count and Say

6. 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".

这个题目表面上说的是Z字形,其实就是把一维字符串从上到下,从下到上这样往复排列,然后把每一行拼接起来。

代码实现

class Solution {
public:
    string convert(string s, int numRows) {
        int slen = s.length();
        string res;
        if(slen <= numRows || numRows <= 1) return s;
        vector<vector<char>> str(slen);
        bool dir = true;
        int ind = 0;
        for(int i = 0; i < slen; i++) {
            str[ind].push_back(s[i]);
            if(ind >= numRows - 1) {
                dir = false;
                ind--;;
            }
            else {
                if(!dir && ind) ind--;
                else{ ind++; dir = true; }
            }
        }
        for(int j = 0; j < numRows; j++) 
            res += string(str[j].begin(), str[j].end());
        return res;
    }
};

38. Count and Say

题目描述

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, …

  • 1 is read off as “one 1” or 11.
  • 11 is read off as “two 1s” or 21.
  • 21 is read off as “one 2, then one 1” or 1211.
  • Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

这道题目的题目意思比较难费解,其实就是这样的:
如果n =1, 那么就是“1”。 n=2,对前面的“1”进行描述就是一个1,那就是“11”。n = 3的时候,对“11”进行描述就是“21”,前面一个数字表示这个数字连续有几个,后面一个数字表示是什么数字。然后“21”就是“1211”。下一个就是“111221”,再下一个就是“312211”

代码实现

class Solution {
public:
    string countAndSay(int n) {
        string res = "1";
        int count = 0;
        for(int i = 0; i < n-1; i++) {
            int fstlen = res.length();
            string tmp;
            for(int j = 0; j < fstlen; j++) {
                count = 1;
                while(j+1 < fstlen && res[j] == res[j+1]) {j++; count++;}
                tmp.push_back(char('0'+count));
                tmp.push_back(res[j]);
            }
            //cout << tmp << endl;
            res = tmp;
        }
        return res;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值