GCD LeetCode 23. Euclidean string

Title Description

For strings S and T, only S = T + ... + time T (T connected to itself one or more times), we identified "T S can be divisible."

Returns the longest string X, X can meet the requirements, and X can be divisible divisible str1 str2.

 

Example 1:

Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"


Example 2:

Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:

Input: str1 = "LEET", str2 = "CODE"
Output: ""
 

prompt:

. 1 <= str1.length <= 1000
. 1 <= str2.length <= 1000
str1 [I] and str2 [i] uppercase letters

 

Problem-solving ideas

See the title which has the greatest common factor of the word, so the first dictation about the gcd algorithm

private int gcd(int a, int b) {
        return b == 0? a: gcd(b, a % b);
    }

There is always a feeling like easily be able to use it.

In fact, to have this wonderful relationship is not very easy looks between two strings, we hope to find a simple way to identify whether or not solvable.

If they have a common factor abc, then str1 is mm a abc repetition str2 is nn an abc repeated, even up as m + nm + n th abc, if m + nm + n th abc with n + mn + m th abc is the same.

So if str1 + str2 == str2 + str1 means solvable.

We are also very easy to think str1 + str2! = Str2 + str1 is also a necessary and sufficient condition no solution.

When the solvability determined, the optimum length of gcd (str1.length, str2.length) string.

This theory is not always optimal length to achieve it? Yes.

Because if it can be recycled to the divisor for the length of the string, naturally, it can be recycled to the length of the string, the length of this theory is that we are looking for the optimal solution.

Just write to those put together is a solution.

code show as below

class Solution {
    public String gcdOfStrings (str1 String, String str2) {
         // assumed str1 by N x, M is a str2 x, then str1 + str2 must be equal to str2 + str1. 
        IF (! (str1 + str2) .equals (+ str2 str1)) {
             return "" ; 
        } 
        // Euclidean requirements gcd. 
        return str1.substring (0 , GCD (str1.length (), str2.length ())); 
    } 

    Private  int GCD ( int A, int B) {
         return B == 0 A:? GCD (B, A% B ); 
    } 
}

 

 

 

Guess you like

Origin www.cnblogs.com/Transkai/p/12468142.html