[LeetCode][JAVA] 1071. Greatest Common Divisor of Strings

탱귤생귤·2023년 10월 26일
0

LeetCode

목록 보기
2/16

https://leetcode.com/problems/greatest-common-divisor-of-strings/
I tried a lot, but I failed..😟

The solution showed me two ways to solve the problem, and I liked the GCD.

It is using Euclidean algorithm. This is my first time learning this algorithm.

class Solution {
     public static String gcdOfStrings(String str1, String str2) {
	    	if(!(str1+str2).equals(str2+str1)) return "";
	    	
    		int i=GCD(str1.length(),str2.length());
    		return str1.substring(0,i);
	    	
	    	
	    }

		public static int GCD(int s1, int s2) {
			if(s2==0) return s1;
            else return GCD(s2,s1%s2);
		}
}

0개의 댓글