判斷一個字符串中是否只含有相同的子字符串(子串長度>=2)

import java.util.*;

/**
 *功能描述:判斷一個字符串中是否只含有相同的子字符串(子串長度>=2)
 輸入:abab
 返回:true
 輸入:abcd
 返回:false
循環查找的辦法:從首字符處截取長度爲2的字符串,在以後的字符串裏看,是否包含。然後往後移,接着截長度爲2的字符串並判斷。
接着是長度爲3的字符串,長度爲4的字符串。直到字符串的一半長度。對長度爲1,2,3的字符串單獨處理。
 */
public class CheckStr {
    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        boolean result=false;
        System.out.println("請輸入一串字符:");
        String str = in.nextLine();
        in.close();
        if(str.length()==1 || str.length()==2){
            System.out.println("輸入的字符串長度爲"+str.length()+",不足以拆分,請輸入3以上長度的字符串。");
        }else{
            result = checkString(str);
        }
        System.out.println("結果--" + result);
    }
    public static boolean checkString(String str) {
        boolean result=false;
        if(str.length()==3){
            if((str.charAt(0)==str.charAt(1))&&(str.charAt(0)==str.charAt(2))){
                result=true;
            }
        }else{
            for(int i=2;i<=str.length()/2&&(result==false);i++){
                    for(int j=0;j<=str.length()-i;j++){
                        String strP=str.substring(j,j+i);
                        if(str.indexOf(strP,j+1)!=-1){
                            result=true;
                            break;
                        }
                    }
                }
            }
        return result;
}
   }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章