Java Algorithm Modern Poetry Like Earthworms

Question description

Modern poetry is like an earthworm
  It will not die even if it is broken into several pieces
  A string of characters is broken into several pieces
  It may be exactly the same
  Please write a program
  Input a string
  Output the maximum number of identical pieces that the string can be broken into substring

Input
Input description:
  One line, one string
Input example:< a i=4> abcabcabcabc

output

Output description:
  One line, a positive integer indicating the maximum number of truncation that the string can be broken into
Output sample:
4

HINT: Time limit: 1.0s Memory limit: 256.0MB
  Can be broken into up to four "abc", that is, abc repeated four times is the original string
  It can also be broken into two "abcabc"
  The worst case is to break into one original string "abcabcabcabc"

Problem-solving ideas

Determining how many paragraphs can be divided is actually to first determine how many times the first letter appears repeatedly, and then determine whether the letters between the first letters are also repeated.

code

import java.util.Scanner;

public class Main {
    
    

    public static void main(String[] args) {
    
    
        Scanner scanner=new Scanner(System.in);
        String s=scanner.next();
        for (int i = 1; i < s.length(); i++) {
    
    
            if (s.length() % i == 0) {
    
                  //判断是否能整除
                if (s.charAt(0) == s.charAt(i)) {
    
                //判断第一个字母是否相同
                    boolean b = true;
                    for (int j = 0; j < s.length() - i; j++) {
    
    
                        if (s.charAt(j) != s.charAt(i + j)) {
    
           //判断每隔i个字母后是否相等 也就是判断是否可以分成i段
                            b = false;
                            break;
                        }
                    }
                    if (b) {
    
    
                        System.out.println(s.length() / i);         //输出可以分出的段数
                        break;
                    }
                }
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/joreng/article/details/123745051