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();
    	}
    
  • 相关阅读:
    12.19手动 项目部署
    12.19 redis缓存
    12.19 redis缓存
    用压测模拟并发、并发处理(synchronized,redis分布式锁)
    12.19 异常捕获补充
    app提交版本更新的流程
    变量
    类型转换的判别
    本文档中使用的伪类型
    Callbacks
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4490638.html
Copyright © 2011-2022 走看看