712681. Better String

Hard

Better String

Summary

Given a string S, we need to find the maximum number of substrings that start and end with the same character. This problem involves dynamic programming and recursion concepts.

Detailed Explanation

The approach to this problem is to use dynamic programming. We create an array dp where dp[i][j] represents whether the substring from index i to j (inclusive) starts and ends with the same character.

We start by initializing a 2D array of size len(S)+1, where dp[i][i] = true for all i because single characters always satisfy the condition. Then we iterate over the string S and check if the current character is equal to both left and right boundaries of the substring. If it is, we update dp[left][right] = true.

To calculate the maximum number of substrings that start and end with the same character, we simply count the number of elements in dp where the value is true.

Here's a step-by-step breakdown:

  1. Create an array dp where dp[i][j] represents whether the substring from index i to j (inclusive) starts and ends with the same character.
  2. Initialize dp[i][i] = true for all i because single characters always satisfy the condition.
  3. Iterate over the string S:
    • For each character, check if it is equal to both left and right boundaries of the substring.
    • If it is, update dp[left][right] = true.
  4. Count the number of elements in dp where the value is true.

The time complexity for this solution is O(len(S)^2) because we are iterating over the string S twice: once to initialize the dp array and once to count the maximum number of substrings that start and end with the same character. The space complexity is also O(len(S)^2) because we need to store all possible substring combinations.

Optimized Solutions

Java

View on GeeksforGeeks
public int betterString(String S) {
    int n = S.length();
    boolean[][] dp = new boolean[n][n];
    
    for (int i = 0; i < n; i++) {
        dp[i][i] = true;
    }
    
    for (int i = 0; i < n - 1; i++) {
        if (S.charAt(i) == S.charAt(i + 1)) {
            dp[i][i + 1] = true;
        }
    }
    
    int maxCount = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            if (S.charAt(i) == S.charAt(j)) {
                maxCount += dp[i][j] ? 1 : 0;
            }
        }
    }
    
    return maxCount;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.