zoukankan      html  css  js  c++  java
  • [LeetCode]Count and Say

    1 题干

      相信大家第一次在leetcode上看到这道题的时候会觉得不知道表达的什么意思,而且还是英文版的,我也是那样,自己在网上搜索查看,找到很多别人写的文章,理解了其中的意思,在这里为自己也做一个简单的描述,首先请看下面的题目内容

    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 的时候查看上一个字符串的个数,因为上一个字符串是一个1,所以返回的是11,当n=3的时候,因为上一个字符串为11,是两个1,所以返回的结果就是21。就是这样以此类推。

    2 代码

       在第一次自己手动编写代码的时候,思路是这样:将得到的字符串转换为字符数组,然后进行一个循环的遍历比较,进行计数,但是并没有使用到递归的思想,导致没有成功。后来在看了别人的文章之后,得到突破,将问题处理掉,源地址来自于这里。大家也可以参看。

    public static String countSay(int n) {
    		// 开始n=1的时候,单独处理
    		if (n == 1) {
    			return "1";
    		}
    		// 递归方法
    		String str = countSay(n - 1) + "*";// 加一个后缀方便在循环中"处理"掉
    		char[] cs = str.toCharArray();
    		String s = "";
    		int count = 1;
    		for (int i = 0; i < cs.length-1; i++) {
    			if (cs[i] == cs[i + 1]) {
    				count++;
    			} else {
    				s = s + count + cs[i];
    				count = 1;
    			}
    		}
    		return s;
    	}
    

    3 总结

      在代码中的加上*号是为了便于字符之间的比较。使用递归思想。特殊情况单独处理。

    安静男孩
  • 相关阅读:
    ubuntu安装谷歌浏览器
    Andoid之硬件访问服务1(让Andoid应用程序访问c库)
    JNI intArray
    JNI Hello World
    Ubuntu 14.04 Sublime Text3 Java编译运行(最简单的方法)
    Python中sys.argv的用法
    python连接mysql数据库
    python中join()函数讲解
    python中split()函数讲解
    深度学习入门教程
  • 原文地址:https://www.cnblogs.com/xishaohui/p/7605701.html
Copyright © 2011-2022 走看看