求字串A與字串B的最長公用字串(JAVA)

來源:互聯網
上載者:User

標籤:字串   java   

思路:引入一個矩陣的思想,把字串A(長度為m)當成矩陣的行,把字串B(長度為n)當矩陣的列,這樣就構成一個m*n的矩陣。若該矩陣的節點對應的字元相同,即m[i]=n[j]時,該節點值為1;當前字元相同節點的值 = 左上方(d[i-1, j-1])的值 +1,這樣當前節點的值就是最大公用子串的長。只需以行號和最大值為條件即可截取最大子串。

public String getLongest(String s1,String s2){        if(s1==null ||s2==null){            return null;        }        if(s1.equals(s2)){            return s1;        }        int length = 0;          int end = 0;          int[][] a = new int[s1.length()][s2.length()];          char[] char1=s1.toCharArray();        char[] char2=s2.toCharArray();        for (int i = 0; i < s1.length(); i++)          {              for (int j = 0; j < s2.length(); j++)              {                  int n = (i - 1 >= 0 && j - 1 >= 0) ? a[i - 1][j - 1] : 0;                  //當前值為上一結點值加1即a[i][j]=a[i-1][j-1]+1;                a[i][j] =(char1[i] == char2[j]) ? 1+n : 0;                 //判斷是否大於之前的最長字串長度                if (a[i][j] > length)                  {  //保持length為最長公用字串長度                    length = a[i][j];                      //end 為最長公用字串末尾                    end = i;                  }              }          }          return s1.substring(end - length + 1, end+1);       }

求字串A與字串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.