leetcode38:Count and Say

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Somnus_k/article/details/82801784

思路:对每个字符串判断连续相同为的个数,然后进行拼接即可。

代码:

public class CountAndSay {

	public static void main(String[] args) {
		System.out.println(countAndSay(1));
	}

	public static String countAndSay(int n) {

		String s = "1";
		StringBuilder sb = null;
		int count = 1;
		for (int i = 2; i <= n; i++) {
			sb=new StringBuilder();
			count=1;
			for (int j = 0; j < s.length(); j++) {
				if (j < s.length() - 1)
					if (s.charAt(j) == s.charAt(j + 1))
						count++;
					else {
						sb = sb.append(count).append(s.charAt(j));
						count = 1;
					}
				else
					sb=sb.append(count).append(s.charAt(j));
			}
			s=sb.toString();
			//System.out.println(s);
		}
		return s;

	}
}

输出:

猜你喜欢

转载自blog.csdn.net/Somnus_k/article/details/82801784