求兩個字串的最長公用子串——Java實現

來源:互聯網
上載者:User

標籤:def   公用子串   bubuko   oid   sys   img   current   bcd   bst   

要求:求兩個字串的最長公用子串,如“abcdefg”和“adefgwgeweg”的最長公用子串為“defg”(子串必須是連續的)

public class Main03{// 求解兩個字元號的最長公用子串public static String maxSubstring(String strOne, String strTwo){// 參數檢查if(strOne==null || strTwo == null){return null;}if(strOne.equals("") || strTwo.equals("")){return null;}// 二者中較長的字串String max = "";// 二者中較短的字串String min = "";if(strOne.length() < strTwo.length()){max = strTwo;min = strOne;} else{max = strTwo;min = strOne;}String current = "";// 遍曆較短的字串,並依次減少短字串的字元數量,判斷長字元是否包含該子串for(int i=0; i<min.length(); i++){for(int begin=0, end=min.length()-i; end<=min.length(); begin++, end++){current = min.substring(begin, end);if(max.contains(current)){return current;}}}return null;}public static void main(String[] args) {String strOne = "abcdefg";String strTwo = "adefgwgeweg";String result = Main03.maxSubstring(strOne, strTwo);System.out.println(result);}}

  

總覺得這題,輸出結果和題意不相符合,結果2,是不是把B序列翻轉,求出兩者最長公用子串

求兩個字串的最長公用子串——Java實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.