Leet code: - 1071 "Greatest Common Divisor of Strings"
solve with recursion:
Time Complexity: O(n)
Space Complexity: O(n)
Solution Link: - https://leetcode.com/problems/greatest-common-divisor-of-strings/solutions/5655486/using-recursion/
Code: -
class Solution {
public String gcdOfStrings(String str1, String str2) {
if(str2.length() > str1.length()){
return gcdOfStrings(str2,str1);
}else if(str1.equals(str2)){
return str1;
}else if(str1.startsWith(str2)){
return gcdOfStrings(str1.substring(str2.length()),str2);
}
return "";
}
}
Comments
Post a Comment