Java╲从一个字符串中截取首尾字符相同、中间字符不重复的子字符串,打印满足该条件中最长的子字符串

/**
* 从一个字符串中取出首位相同但内部字符都最多只能出现一个的最长子字符串 第一层:从左边第一个字符开始遍历字符串,截取与这个字符可以组成首位相同的子字符串
* 第二层:将截取的首尾相同的字符串的首尾字符去掉,再次进入第一层的验证,如果内部没有相同字符了,就返回去掉首尾字符之前的字符串(只有在长度大于),如果有,继续重复第二层验证
*
* @author jiang
*/

public class StringSplit {
    // 传入一个字符串,获取其中的首尾相同的字符串
    String split(String str) {
        // 默认值为null表示如果str中没有一个首尾相同的子字符串,则返回null
        String result = "";
        for (int i = 0; i < str.length() - 1; i++) {
            char a = str.charAt(i);
            int index2 = str.indexOf(a, i + 1);
            if (index2 == -1) {// 如果后面没有第二个a代表的字符了
                continue;// 继续看下一个位置的字符
            } else {// 后面有第二个a字符
                String s = str.substring(i, index2 + 1);// 截取出这个首位字母相同的字符串
                System.out.println("s->" + s);
                String child = splitChild(s);// 递归得到s的最简字符串,有可能是s本身
                System.out.println("child->" + child);
                if (child.length() > result.length()) {// 如果这个最简字符串的长度大于原本用于返回的字符串
                    result = child;// 就把返回的字符串变为这个最简子字符串
                }
            }
        }
        return result;
    }

    // 传入一个首尾字符相同的字符串,判断里面是否还有首尾相同的子字符串
    String splitChild(String str) {
        String result = str;// 默认值为str,表示如果str里没有其他首尾相同的子字符串,则返回它本身
        // 截取出第二个字符为首位,倒数第二个字符为末尾的字符串
        String s = str.substring(1, str.length() - 1);
        // 判断这个字符串内是否有首尾相同的子字符串
        String s1 = split(s);
        if (s1 == "") {
            return result;
        } else {
            return s1;
        }
    }

    public static void main(String[] args) {
        String s = "9qwertytuiopasdfgghjkl99asdfghjtfba121sdsaefva121asdfghjkl1";
        System.out.println(new StringSplit().split(s));
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值