My JAVA Solution with regex


  • 2
    L
    public class Solution {
        public boolean repeatedSubstringPattern(String str) {
            if(str == null || str.length() < 2) return false;
            
            boolean result = false;
            for(int i = 1; i <= str.length()/2; i++) {
                if(str.length()%i != 0) continue;
                String regex = "("+str.substring(0,i)+")" + "+";
                result = result | str.matches(regex);
            }
            return result;
        }
    }
    

  • 0
    L

    Great idea, but why regex in java is so much slower than normal string matching?


  • 0
    L
    public class Solution {
        public boolean repeatedSubstringPattern(String str) {
            if(str == null || str.length() < 2) return false;
            
            for(int i = 1; i <= str.length()/2; i++) {
                if(str.length()%i != 0) continue;
                String regex = "("+str.substring(0,i)+")" + "+";
                if(str.matches(regex)) return true;
            }
            return false;
        }
    }
    

    I have no idea about you question. The above solution wiil be better.


  • 0
    D

    or

    return s.matches("^(.+)\\1{1,}$");
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.