zoukankan      html  css  js  c++  java
  • Leetcode: 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.

    题目描述不清, WA 了一次

    Input:6 Output:"21112211" Expected:"312211"

    思路:

    1. 计数, 前进

    代码:

    class Solution {
    public:
        string countAndSay(int n) {
            string prestr = "1", curstr;
    		if(n == 1)
    			return prestr;
    
    		for(int i = 1; i < n; i ++) {
    			curstr = generateNext(prestr);
    			prestr = curstr;
    		}
    		return curstr;
        }
    	string generateNext(const string &prestr) {
    		string str;
    		for(int i = 0; i < prestr.size(); i ++) {
    			int n = countSame(prestr, i);
    			str.push_back(n+'0');
    			str.push_back(prestr[i]);
    			i += n-1;
    		}
    		return str;
    	}
    	int countSame(const string &prestr, int i) {
    		if(i >= prestr.size()) return 0;
    
    		int cnt = 1, prechar = prestr[i];
    		i++;
    		while(i < prestr.size()) {
    			if(prestr[i] == prechar) {
    				cnt++;
    				i++;
    			}else{
    				return cnt;
    			}
    		}
    		return cnt;
    	}
    };
    

      

  • 相关阅读:
    PHP编译安装
    PHP编译安装
    Apache编译安装
    Apache编译安装
    端口号
    端口号
    初步理解TCP/IP网络
    初步理解TCP/IP网络
    剑指offer——树的子结构
    STL四种智能指针
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3510741.html
Copyright © 2011-2022 走看看