How to find the longest repeated substring of given string

前端 未结 2 1747
逝去的感伤
逝去的感伤 2021-01-07 13:35

I am new java and I was given assignment to find the longest substring of a string. I research online and seems that good way of approaching this problem will be implementi

2条回答
  •  一向
    一向 (楼主)
    2021-01-07 14:03

    public static void main(String[] args) {
            String str = "testingString";
            char[] strArr = str.toCharArray();
            StringBuilder bm = new StringBuilder();
            boolean isPresent = false;
            int len = strArr.length;
            int initial =0;
            int dinitial=0;
    
            HashMap hm = new HashMap();
            HashMap hl = new HashMap();
            while(initial<=len-1 && !(dinitial>=len-1)){
                if(!hm.isEmpty()){
                    isPresent = hm.containsValue(strArr[initial]+"");
                    if(!isPresent){
                        bm.append(strArr[initial]);
                        hm.put(strArr[initial]+"",strArr[initial]+"");
                        if(initial==len-1){
                            System.out.println("Longest substring is::" + bm);
                            break;
                        }
                    }
                    else if(isPresent){
                        System.out.println("Longest substring is::" + bm);
                        bm.delete(0, bm.length());
                        ++dinitial;
                        initial--;
                        hm.clear();
                    }
                    initial++;
                }
                else
                {
                        bm.append(strArr[initial]);
                        hm.put(strArr[initial]+"",strArr[initial]+"");
                        initial++;
                }
            }
            hm.clear();
        }
    

提交回复
热议问题