【leetcode】38. (Easy)Count and Say

题目链接

解题思路:
这道题的意思是从1开始:
1: 读作1个1,即11,下一个就是11
11:读作2个1,即21,下一个就是21
21:读作1个2,1个1,下一个就是1211

依次类推

我的想法是控制两个循环while1 while2,在外循环进行迭代判断,比如如果输入n=3,就循环2次,从n=1开始迭代计算n=3时的情况;
内循环具体计算每个单元stmp的内容,比如当上一个s是“21”时,第一个stmp=“12”即1个2,循环到第二个stmp是“11”即1个1

看了网上的代码,基本上都是这个思路

提交代码:

class Solution {
	public String countAndSay(int n) {
		if (n == 1)		return "1";

		String stmp,s = "1",snext="";
		int p,charcnt, charvalue;
		while (n > 1) { // 迭代的次数
			p = 0;
			while (p < s.length()) {
				charcnt = 0;
				charvalue = s.charAt(p);
				while (p < s.length() && s.charAt(p) == charvalue) {
					p++;
					charcnt++;
				}
				stmp = Integer.toString(charcnt);
				stmp += String.valueOf((int) (charvalue - '0'));
				snext += stmp;
			}
			s = snext;snext = "";n--;
		}
		return s;
	}
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/83443399