lc1071 Greatest Common Divisor of Strings
Get two longest common substring of string
Assumptions: str1.length> str2.length
Because it is common string, and so on will be able str1 str2 matching the front part, or do not exist common substring.
So we compare the str1 str2 and 0 ~ str2.length () - 1 part,
If different, the process directly returns "", the absence of common substrings.
If the same, the comparison continues str2 str1 and the remaining part of, this is recursion, call the original function gcd (str2, str1.substring (str2.length))
There are some details:
Such as always to ensure str1> str2, can use a if (str1 <str2) {swap (str1, str2)}
str1 == str2 direct examination str1.equals (str2)
1 class Solution { 2 public String gcdOfStrings(String str1, String str2) { 3 return GCD(str1, str2); 4 } 5 public String GCD(String a, String b) { 6 if(a.length() > b.length()) { 7 for(int i = 0; i < b.length(); i++){ 8 if(b.charAt(i) != a.charAt(i)){ 9 return ""; 10 } 11 } 12 String temp = a.substring(b.length()); 13 return GCD(temp,b); 14 } 15 else if(b.length() > a.length()) 16 return GCD(b, a); 17 else 18 return a.equals(b) ? a : ""; 19 } 20 }