【華為機試075】公共字串計算
阿新 • • 發佈:2018-12-24
題目描述:
計算兩個字串的最大公共字串的長度,字元不區分大小寫
Java實現:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String str1 = sc.next(); String str2 = sc.next(); System.out.println(maxComSubstring(str1, str2)); } } private static int maxComSubstring(String str1, String str2) { int max = 0; int[][] dp = new int[str1.length()][str2.length()]; for(int i = 0; i < str1.length(); i++) { if((str1.charAt(i)+"").equalsIgnoreCase(str2.charAt(0)+"")) dp[i][0] = 1; } for(int j = 0; j < str2.length(); j++) { if((str1.charAt(0)+"").equalsIgnoreCase(str2.charAt(j)+"")) dp[0][j] = 1; } for(int i = 1; i < str1.length(); i++) { for(int j = 1; j < str2.length(); j++) { if((str1.charAt(i)+"").equalsIgnoreCase(str2.charAt(j)+"")) { dp[i][j] = dp[i-1][j-1] + 1; if(dp[i][j] > max) { max = dp[i][j]; } } } } return max; } }
知識點:
- 注意dp的初始化