zoukankan      html  css  js  c++  java
  • Count and Say

    package cn.edu.xidian.sselab.string;

    /**
     *
     * @author zhiyong wang
     * title: Count and Say
     * content:
     * 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.
     *
     */
    public class CountAndSay {

        //这个题主要是理解题意,理解了题意就好做了,其实就是一个时间复杂度为O(N^2)操作,第一层是对n从1开始进行遍历,第二层是求每一层的数值
        public String countAndSays(int n){
            String s = "1";
            for(int i=1;i<n;i++){
                s = countAndSay(s);
            }
            return s;
        }
        public String countAndSay(String s){
            char[] ch = s.toCharArray();
            int len = ch.length;
            StringBuilder sb = new StringBuilder();
            if(len == 1) sb.append(1).append(s);
            int i=0;
            int j = 0;
            while(i<len-1){
                j = 0;
                while(i< len-1 && ch[i] == ch[i+1]){
                    i++;
                    j++;
                }        
                sb.append(j+1).append(ch[i]);
                i++;
            }
            if(len > 1 && ch[len-1] != ch[len-2]){
                sb.append(1).append(ch[len-1]);
            }
            return sb.toString();            
        }
    }

  • 相关阅读:
    有序数组(类模板)
    BUUCTF-Web Comment
    BUUCTF-web NiZhuanSiWei
    2020数字中国创新大赛虎符网络安全赛道-pwn count
    BUUCTF-Web Easy Calc
    xctf-web fakebook
    xctf-web supersqli
    xctf-pwn pwn200
    xctf-pwn level3
    利用updatexml()报错注入mysql
  • 原文地址:https://www.cnblogs.com/wzyxidian/p/5218830.html
Copyright © 2011-2022 走看看