leetcode38countAndSay

package com.javamvc.learning.leetcode;

public class leetcode38countAndSay {

   	public static void main(String[] args) {
   	
	leetcode38countAndSay leetcode38 = new  leetcode38countAndSay();
	Solution solution = leetcode38.new Solution();
	String countAndSay = solution.countAndSay(10);
	System.out.println(countAndSay);
	
}	
	class Solution {
	    public String countAndSay(int n) {
	        if (n == 1) {
	            return "1";
	        }
	        
	        if (n == 2) {
	            return "11";
	        }
	        
	        StringBuilder ans = new StringBuilder();
	        String previous = countAndSay(n - 1);
	        
	        for (int i = 1; i < previous.length(); i++) {
	            int count = 1;
	            char temp = previous.charAt(i - 1);
	            while (i < previous.length() && previous.charAt(i) == temp) {
	                count++;
	                i++;
	            }
	            
	            ans.append(count);
	            ans.append(temp - '0');
	            
	            if (i == previous.length() - 1) {
	                ans.append(1);
	                ans.append(previous.charAt(previous.length() - 1) - '0');
	            }
	        }
	        
	        return ans.toString();
	    }
	}
	}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42664961/article/details/82979765
今日推荐