首页 > 试题广场 >

计算重复字符串长度

[编程题]计算重复字符串长度
  • 热度指数:200 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 128M,其他语言256M
  • 算法知识视频讲解
请从字符串中找出至少重复一次的子字符串的最大长度

输入描述:
字符串,长度不超过1000


输出描述:
重复子串的长度,不存在输出0
示例1

输入

ababcdabcefsgg

输出

3

说明

abc为重复的最大子串,长度为3
import java.util.Scanner;

/**
 * 请从字符串中找出至少重复一次的子字符串的最大长度
 * 输入描述:
 * 字符串,长度不超过1000
 * 输出描述:
 * 重复子串的长度,不存在输出0
 * 输入例子1:
 * ababcdabcefsgg
 * 输出例子1:
 * 3
 */
public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int count = findLongestRepeatStr(sc.nextLine());
        System.out.println(count + "");
    }


    public static int findLongestRepeatStr(String str) {
        int len = str.length();

        int array[][] = new int[len + 1][len + 1];
        for (int m = 0; m < len; m++) {

            for (int n = 0; n < len; n++) {
                if (str.charAt(m) == str.charAt(n))
                    array[m + 1][n + 1] = array[m][n] + 1;

            }

        }

        int max = 0;
        for (int m = 0; m < len + 1; m++) {

            for (int n = 0; n < len + 1; n++) {
                if ((m != n) && (array[m][n] > max))
                    max = array[m][n];
            }

        }

        return max;

    }
}
发表于 2018-07-08 19:08:35 回复(0)
import java.util.Scanner;

public class Main {
    Main() {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        int max=0;
        String temp;
        for (int i = 1; i <str.length() ; i++) {//子串长度
            for (int k = 0; k < str.length()-i; k++) {//
                temp=str.substring(k, k + i);
                if (str.substring(0, k).contains(temp) || str.substring(k+i).contains(temp)) {//字符串中:子串前和后有没有和子串一样的子串
                    if(max<temp.length()) max = temp.length();
                }
            }
        }
        System.out.println(max);
    }

    public static void main(String[] args) {
        new Main();
    }

}
发表于 2018-08-14 14:01:47 回复(0)
#include <iostream>
#include <string>
#include <vector>

using namespace std;

inline int getResult(const string& str) {
    int len = str.size();
    vector<vector<int>> arr;
    arr.resize(len);
    for(int n = 0 ; n < len; ++n) {
        arr[n].resize(len);
    }
    for(int i = 0; i < len;++i) {
        for(int j = 0 ; j < len;++j) {
            if(str[i] == str[j]) {
                arr[i][j] = (i - 1 >= 0 && j - 1 >= 0) ? arr[i - 1][j - 1] + 1 : 1;
            }
        }
    }
    
    auto max = 0;
    for(int i = 0; i < len;++i) {
        for(int j = 0 ; j < len;++j) {
            if(i != j && arr[i][j] > max) {
                max = arr[i][j];
            }
        }
    }
    return max;
}

int main() {
    string str;
    while(cin>>str) {
        auto res = getResult(str);
        cout<<res<<endl;
    }
    
}

发表于 2018-07-09 20:38:17 回复(0)