JAVA重復疊加字符串匹配


給定兩個字符串 A 和 B, 尋找重復疊加字符串A的最小次數,使得字符串B成為疊加后的字符串A的子串,如果不存在則返回 -1。

舉個例子,A = "abcd",B = "cdabcdab"。

答案為 3, 因為 A 重復疊加三遍后為 “abcdabcdabcd”,此時 B 是其子串;A 重復疊加兩遍后為"abcdabcd",B 並不是其子串。

鏈接:https://leetcode-cn.com/problems/repeated-string-match

思路:分類討論,理論上來說,如果m>=n,那么只可能返回1,-1,2,如果m<n,那么就要考慮至少要重疊幾次,我認為應該是重疊后的串至少要大於m+n

否則就返回-1

class Solution {
    public int repeatedStringMatch(String s1, String s2) {
        int cnt = 1;
        String s = s1 ;
        int n = s1.length();
        int m = s2.length();
        if(n<m)
        {
            while(s.length()< (n+m) )
            {
                s = s+s1 ;
                cnt++;
                if(s.indexOf(s2)!=-1)
                {
                    return cnt ;
                }
            }
            return -1 ;
        }
        else //n>=m 只能返回-1,1,2
        {
            String s3 =s1+s1 ;
            if(s1.indexOf(s2)!=-1) return 1;
            else if(s3.indexOf(s2)!=-1) return 2 ;
            else return  -1 ;
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM