zoukankan      html  css  js  c++  java
  • repeated-substring-pattern

    https://leetcode.com/problems/repeated-substring-pattern/

    下面这个方法,开始我觉得挺好。可惜还是超时了。后来我就加了一个剪枝策略,只有长度能够整除总长度的子串,才需要进行比较。

    package com.company;
    
    
    import java.util.*;
    
    class Solution {
        public boolean repeatedSubstringPattern(String str) {
    
            for (int i=1; i<=str.length()/2; i++) {
                if (str.length() % i != 0) {
                    continue;
                }
                StringBuilder sb = new StringBuilder();
                sb.append(str.substring(i));
                sb.append(str.substring(0, i));
                if (str.equals(sb.toString())) {
                    return true;
                }
            }
            return false;
        }
    }
    
    public class Main {
    
        public static void main(String[] args) throws InterruptedException {
    
            System.out.println("Hello!");
            Solution solution = new Solution();
    
            // Your Codec object will be instantiated and called as such:
            String str = "abcabcabcc";
            boolean ret = solution.repeatedSubstringPattern(str);
            System.out.printf("ret:%b
    ", ret);
    
            System.out.println();
    
        }
    
    }

    下面是开始超时的方法,少了一个剪枝条件。

    package com.company;
    
    
    import java.util.*;
    
    class Solution {
        public boolean repeatedSubstringPattern(String str) {
    
            for (int i=1; i<=str.length()/2; i++) {
                StringBuilder sb = new StringBuilder();
                sb.append(str.substring(i));
                sb.append(str.substring(0, i));
                if (str.equals(sb.toString())) {
                    return true;
                }
            }
            return false;
        }
    }
    
    public class Main {
    
        public static void main(String[] args) throws InterruptedException {
    
            System.out.println("Hello!");
            Solution solution = new Solution();
    
            // Your Codec object will be instantiated and called as such:
            String str = "abcabcabcc";
            boolean ret = solution.repeatedSubstringPattern(str);
            System.out.printf("ret:%b
    ", ret);
    
            System.out.println();
    
        }
    
    }
  • 相关阅读:
    js阶段循环(for,while,do-while,for-in),判断(if,switch),练习题
    翻牌器
    用 VSCode 调试网页的 JS 代码
    图形化设置数据库规则
    js中ES6数据结构Map 、Set 、WeakMap 、 WeakSet
    css的filter方法,给图片添加滤镜
    使用<a-select>时,placeholder不起作用,提示语不显示
    Vue数据更新但页面没有更新的多种情况
    react事件处理-函数绑定
    在css中使用js定义的变量
  • 原文地址:https://www.cnblogs.com/charlesblc/p/6075958.html
Copyright © 2011-2022 走看看