获取字符串中存在影字符串的最大子字符串

写一个算法,获取字符串中存在影字符串的最大子字符串,如字符串"qwer12rewqyuioiuy"中,存在影字符串的最大子字符串是"yuioiuy".
1)   字符串颠倒转换
2)   获取含有首字母的最大反相同字符串,如qwer-->rewq
3)   将获取字符串中存在影字符串的最大子字符串问题转化为获取含有首字母的最大反相同字符串问题
如:qwer12rewqyuioiuy-->wer12rewqyuioiuy-->er12rewqyuioiuy-->......
4)   求字符串中最大的反相同字符串的集合

package com.example.demo.t1;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ypf on 2018/12/13.
 */
public class Test {

    /**
    *   获取字符串中存在影字符串的最大子字符串的集合
    */
    public List<String> getComStr(String str){
        if(null == str || "".equals(str)){
            return null;
        }
        String[] initArr = str.split("");
        int len = initArr.length;
        String[] comStr = new String[len];
        for(int i = 0; i < len; i++){
            String newStr = str.substring(i,len);
            comStr[i] = getFirstCom(newStr);
        }

        int max = 0;
        for(int i = 0; i < len; i++){
            int k = 0;
            if(comStr[i] != null){
                k = comStr[i].length();
            }
            if(k > max){
                max = k;
            }
        }

        List<String> list = new ArrayList<>();
        for(int i = 0; i < len; i++){
            if(comStr[i] != null && comStr[i].length() == max){
                list.add(comStr[i] + " --> " + reversalStr(comStr[i]));
            }
        }
        return list;
    }

    /**
    *   获取含有首个字母的存在影符串的最大字符串
    */
    public String getFirstCom(String str){
        if("".equals(str)){
            return null;
        }
        String[] initArr = str.split("");
        int len = initArr.length;
        for(int i = 0; i < len; i++){
            String newStr = str.substring(0,len - i);
            String reversalStr = reversalStr(newStr);
            if(str.indexOf(reversalStr) != -1){
                return newStr;
            }
        }
        return null;
    }

    /**
    *   字符串颠倒
    */
    public String reversalStr(String str){
        StringBuffer buf = new StringBuffer();
        if(str != null || "".equals(str)){
            String[] initArr = str.split("");
            int len = initArr.length;
            for(int i = 0; i < len; i++){
                buf.append(initArr[len-i-1]);
            }
            return buf.toString();
        }
        return null;
    }

    /**
     * 测试
     * */
    public static void main(String[] args) {
        Test t = new Test();
        String initStr = "qwerty565890-ytrewq0o0jjyp[ugfffghjk--99huiiuh";
        List<String> list = t.getComStr(initStr);
        for(String str:list){
            System.out.println(str);
        }
    }
}

测试结果如下:

Connected to the target VM, address: '127.0.0.1:64784', transport: 'socket'
qwerty --> ytrewq
huiiuh --> huiiuh
Disconnected from the target VM, address: '127.0.0.1:64784', transport: 'socket'

Process finished with exit code 0

猜你喜欢

转载自www.cnblogs.com/myxcf/p/10120948.html
今日推荐