1071. Greatest Common Divisor of Strings

Naive

```java
class Solution {
    public String gcdOfStrings(String str1, String str2) {
        int len1 = str1.length();
        int len2 = str2.length();
        if (len1 == len2) {
            if (str1.equals(str2)) {
                return str1;
            } else {
                return "";
            }
        }
        String result = "";
        if (len1 > len2) {
            result = helper(str1, str2);
        } else {
            result = helper(str2, str1);
        }
        return result;
    }
    private String helper(String s1, String s2) {
        for (int i = s2.length(); i >= 1; i--) {
            String subStr = s2.substring(0, i);
            String temp1 = new String(s1);
            String temp2 = new String(s2);
            temp1 = temp1.replace(subStr, "");
            temp2 = temp2.replace(subStr, "");
            //System.out.println("subStr:" + subStr + "temp:" + temp);
            if (temp1.isEmpty() && temp2.isEmpty()) {
                return subStr;
            }
        }
        return "";
    }
}

/**

 */
```

GCD

Last updated

Was this helpful?