zoukankan      html  css  js  c++  java
  • Java for LeetCode 038 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时返回“11”,n=3时返回"21",n=4时返回"1211"
    所以肯定是用递归也进行求解,JAVA实现如下:

    	static public String countAndSay(int n) {
    		if(n==1)
    			return "1";
    		return countAndSay(countAndSay(n-1));
    	}
    	
    	static String countAndSay(String s){
    		StringBuilder sb = new StringBuilder();
    		int count = 0;
    		char temp='*';
    		for(int i=0;i<s.length();i++){
    			if(temp!=s.charAt(i)){
    				if(temp!='*'){
    					sb.append(count);
    					sb.append(temp);
    				}
    				count=1;
    				temp=s.charAt(i);
    			}
    			else
    				count++;
    		}
    		sb.append(count);
    		sb.append(temp);
    		return sb.toString();
    	}
    
  • 相关阅读:
    webpack学习(一)—— 入门
    AMD 规范
    CommonJS 规范
    webpack 故障处理
    webpack 开发环境
    webpack 插件
    webpack 配置文件
    webpack 使用
    webpack Loader
    webpack常用的插件安装命令
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4490638.html
Copyright © 2011-2022 走看看