1.统计每个月兔子的总数
题目描述
有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?
/**
* 统计出兔子总数。
*
* @param monthCount 第几个月
* @return 兔子总数
*/
public static int getTotalCount(int monthCount)
{
return 0;
}
输入描述:
输入int型表示month
输出描述:
输出兔子总数int型
示例1
输入
9
输出
34
import java.util.Scanner;
public class Main{
public static void main(String []args){
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
int n=sc.nextInt();
System.out.println(getTotalCount2(n));
}
}
//方法1:递归
public static int getTotalCount(int monthCount){
if(monthCount==0) return 0;
else if(monthCount==1) return 1;
else if(monthCount==2) return 1;
else{
return getTotalCount(monthCount-1)+getTotalCount(monthCount-2);
}
}
//方法2:动态规划
public static int getTotalCount2(int m){
int a[]=new int[m+1];
a[0]=0;
a[1]=1;
for(int i=2;i<=m;i++){
a[i]=a[i-1]+a[i-2];
}
if(m==0) return 0;
else if(m==1) return 1;
else {
return a[m-1]+a[m-2];
}
}
}
2. 字符串运用-密码截取
题目描述
Catcher 是MCA国的情报员,他工作时发现敌国会用一些对称的密码进行通信,比如像这些ABBA,ABA,A,123321,但是他们有时会在开始或结束时加入一些无关的字符以防止别国破解。比如进行下列变化 ABBA->12ABBA,ABA->ABAKK,123321->51233214 。因为截获的串太长了,而且存在多种可能的情况(abaaab可看作是aba,或baaab的加密形式),Cathcer的工作量实在是太大了,他只能向电脑高手求助,你能帮Catcher找出最长的有效密码串吗?
输入描述:
输入一个字符串
输出描述:
返回有效密码串的最大长度
示例1
输入
ABBA
输出
4
import java.util.Scanner;
public class Main{
public static void main(String []args){
String s=null;
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
String str=sc.nextLine();
int flag=0;
for(int i=0;i<str.length();i++){
for (int j = str.length(); j >=i; j--) {
s=str.substring(i, j);
if(getStr(s)&&flag==0){
flag=s.length();
}else if(getStr(s)&&flag<s.length()){
flag=s.length();
}
}
}
System.out.println(flag);
}
}
public static boolean getStr(String str){
int len=str.length();
for(int i=0;i<len/2;i++){
if(str.charAt(i)!=str.charAt(len-1-i))
return false;
}
return true;
}
}
b. 算法2:牛客网某大神的笔记,不断前后剪短反转后的子串,查看原字符串是否反转后的子串,若包含输出i
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String input = sc.next();
System.out.println(getNumber(input));
}
}
public static int getNumber(String str){
int result = 1;
StringBuffer sb = new StringBuffer(str);
String temp = sb.reverse().toString();
//获取所有子串,查看原字符串是否包含反转后的子串
for(int i = temp.length(); i >= 1 ;i--){
//i为子串的长度
for(int j = 0; j <= temp.length()-i;j++){
String tempSubString = temp.substring(j,j + i);
if(str.contains(tempSubString)){
return i;
}
}
}
return result;
}
}