困难的子串

 分析:

  1.  char ch = (char) ('A' + i);时记得转为字符,否则会变为A0,A1字符串或者其他字符串
  2.  判断字符串是否为苦难字符串时直接用截取的方法看是否有重复且相邻的字符串

没考虑到以B开头的代码

import java.util.Scanner;

public class Main {
	public static int n;     //第n个最小困难子串
	public static int L;     //前L个大写字母

	public static void main(String[] args) {
		Scanner sca = new Scanner(System.in);		
		n = sca.nextInt();
		L = sca.nextInt();
		String str = new String();
		Todo(0,str);

	}

	private static void Todo(int nt, String str) {
		//跳出递归
		if(nt == n) {
			System.out.println(str);
			return;
		}
		
		//下一个最小困难子串
		for(int i = 0; i < L; i ++) {
			char ch = (char) ('A' + i);
			if(check(ch,str)) {
				str = str + ch;
				System.out.println( nt + ":" +str);
				Todo(nt + 1, str);//无需回溯,因为他不会返回继续使用它
				return;
			}
		}
	}

	private static boolean check(char c, String str) {
		str = str + c;
	 
		int nl = str.length();
		if(nl == 1) {
			return true;
		}
		else {
			for(int i = nl - 1; 2 * i - nl >= 0; i --) {
				String s1 = str.substring(i, nl);
				String s2 = str.substring(i - (nl - i), i );
				 
				if(s1.equals(s2)) {
					
					return false;
				}
			}
		}
		//System.out.println(str);
		return true;
	}

}

运行结果1:

7
3
0:A
1:AB
2:ABA
3:ABAC
4:ABACA
5:ABACAB
6:ABACABA
ABACABA

运行结果2:没有以B开头的情况

错误:他是要回溯情况的,因为字母的变化仍然可以增加结构的种类。所以他是与一般情况下是一样的,需要回溯且遍历 

5
2
0:A
1:AB
2:ABA

 

所以改进的代码为:

分析: 

  1.  每一次的递归大家都共享一个变量nt所以可以将他射着为全局变量,每当一次有一种情况就nt ++
  2.  以下面为例,这样他回溯到B的时候就不会导致nt也跟着回溯而达到不想要的结果
import java.util.Scanner;

public class 困难的子串 {
	public static int n;     //第n个最小困难子串
	public static int L;     //前L个大写字母
	public static int nt = 0;

	public static void main(String[] args) {
		Scanner sca = new Scanner(System.in);		
		n = sca.nextInt();
		L = sca.nextInt();
		String str = new String();
		Todo(str);

	}

	private static void Todo( String str) {
		//跳出递归
		if(nt == n) {
			System.out.println(str);
			return;
		}
		
		//下一个最小困难子串
		for(int i = 0; i < L; i ++) {
			char ch = (char) ('A' + i);
			if(check(ch,str)) {
				String strt ;
				strt = str + ch;
				
				System.out.println( nt + ":" +strt);
				nt ++;
				Todo(strt);
				}
		}
	}

	private static boolean check(char c, String str) {
		char ch = (char)('A' + c);
		str = str + c;
		
		int nl = str.length();
		if(nl == 1) {
			return true;
		}
		else {
			for(int i = nl - 1; 2 * i - nl >= 0; i --) {
				String s1 = str.substring(i, nl);
				String s2 = str.substring(i - (nl - i), i );
				 
				if(s1.equals(s2)) {
				 
					return false;
				}
			}
		}
		 
		return true;
	}

}

运行结果:

5
2
0:A
1:AB
2:ABA
3:B
4:BA
BA

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值