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();
    	}
    
  • 相关阅读:
    CSS——清除浮动
    .net 多线程之线程取消
    .net 多线程临时变量
    NPOI helper
    添加学员存储过程
    SQL-sqlHelper001
    ado.net 中事务的使用
    T-SQL 事务2
    T-SQL 事务
    T-SQL 带参数存储过程
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4490638.html
Copyright © 2011-2022 走看看