Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

38. Count and Say #14

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

题意是n=1时输出字符串1;n=2时,数上次字符串中的数值个数,因为上次字符串有1个1,所以输出11;n=3时,由于上次字符是11,有2个1,所以输出21;n=4时,由于上次字符串是21,有1个2和1个1,所以输出1211。 每一次temp和count和j都要重置!!! public class Solution { public String countAndSay(int n) { String s = "1"; for(int i = 1; i<n; i++){ int len = s.length(); String temp = ""; for(int j = 0; j<len; j++){ int count = 1; while(j+1< len && s.charAt(j) == s.charAt(j+1)){ j ++; count ++; } temp += count+s.substring(j,j+1); } s = temp; } return s; } }