【資料結構與演算法】LCS(不連續)

來源:互聯網
上載者:User

標籤:資料結構   演算法   lcs   動態規劃   

這個問題很經典,典型的動態規劃,動態規劃就是填一個表,然後遍曆一下就行了。

  • 代碼實現

/** * 源碼名稱:LCSequence.java  * 日期:2014-09-02  * 程式功能:LCS(不連續)  * 著作權:[email protected]  * A2BGeek */public class LCSequence {private String mOne, mTwo;int[][] mMatrix;int[][] mB;String mResult;public LCSequence(String one, String two) {mOne = one;mTwo = two;int lengthOne = one.length();int lengthTwo = two.length();mMatrix = new int[lengthOne + 1][lengthTwo + 1];mB = new int[lengthOne + 1][lengthTwo + 1];mResult = "";}public void generateMatrix() {int lengthOne = mOne.length();int lengthTwo = mTwo.length();for (int i = 1; i <= lengthOne; i++) {mMatrix[i][0] = 0;}for (int j = 1; j <= lengthTwo; j++) {mMatrix[0][j] = 0;}mMatrix[0][0] = 0;// 1 stands for upleft, 2 stands for up, 3 stands for leftfor (int i = 1; i <= lengthOne; i++) {for (int j = 1; j <= lengthTwo; j++) {if (mOne.charAt(i - 1) == mTwo.charAt(j - 1)) {mMatrix[i][j] = mMatrix[i - 1][j - 1] + 1;mB[i][j] = 1;} else if (mMatrix[i - 1][j] >= mMatrix[i][j - 1]) {mMatrix[i][j] = mMatrix[i - 1][j];mB[i][j] = 2;} else if (mMatrix[i - 1][j] < mMatrix[i][j - 1]) {mMatrix[i][j] = mMatrix[i][j - 1];mB[i][j] = 3;}}}}public void getLCSequence(String str, int i, int j) {if (i == 0 || j == 0) {return;}if (mB[i][j] == 1) {getLCSequence(str, i - 1, j - 1);mResult += str.charAt(i - 1);} else if (mB[i][j] == 2) {getLCSequence(str, i - 1, j);} else {getLCSequence(str, i, j - 1);}}public void printMatrix(int[][] in) {for (int i = 0; i < in.length; i++) {for (int j = 0; j < in[i].length; j++) {System.out.print(in[i][j] + "   ");}System.out.println();}}public void printMatrix(char[][] in) {for (int i = 0; i < in.length; i++) {for (int j = 0; j < in[i].length; j++) {System.out.print(in[i][j] + "   ");}System.out.println();}}public static void main(String[] args) {String one = "abcbdab";String two = "bdcaba";LCSequence mLcSequence = new LCSequence(one, two);mLcSequence.generateMatrix();mLcSequence.printMatrix(mLcSequence.mMatrix);System.out.println("------------------------");mLcSequence.printMatrix(mLcSequence.mB);mLcSequence.getLCSequence(one, one.length(), two.length());System.out.println(mLcSequence.mResult);}}


【資料結構與演算法】LCS(不連續)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.