Task description:
Imagine you have a long word made up of small letters like "a", "b", "c", ancd so on. Let’s call this word a puzzle word.
We want to look at all the smaller parts (called substrings) of this word. A substring just means some letters that are right next to each other in the word.
Now here’s the challenge: Count how many special parts are hiding inside this puzzle word!
A part is special if it follows one of these rules:
It’s 2 letters long, and both letters are the same. Example: "aa" is special, "ab" is not.
It’s 3 or more letters long, and:
It starts and ends with the same letter
All the letters in the middle are exactly the same letter
Example: "xyyx" is special → it starts and ends with "x", and the middle is just "yy"
Example: If the puzzle word is "xyyx":
Let’s check some parts:
"xy" → Not special
"yy" → Yes! both letters are the same
"xyyx" → Yes! starts and ends with "x", middle is just "y"
So the answer is 2 special parts.
Things to remember: The puzzle word will only have lowercase letters.
The word can be very long, up to 300,000 letters!
Here is my code:
import java.util.*;
class Main {
    public static long special(String word) {
        int n = word.length();
        long count = 0;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int len = j - i + 1;
                String sub = word.substring(i, j + 1);
                if (len == 2) {
                    if (sub.charAt(0) == sub.charAt(1)) {
                        count++;
                    }
                } else if (len > 2) {
                    if (sub.charAt(0) == sub.charAt(len - 1)) {
                        // Check if middle part has exactly 1 distinct character
                        Set<Character> middleChars = new HashSet<>();
                        for (int k = 1; k < len - 1; k++) {
                            middleChars.add(sub.charAt(k));
                            if (middleChars.size() > 1) break;
                        }
                        if (middleChars.size() == 1) {
                            count++;
                        }
                    }
                }
            }
        }
        return count;
    }
    public static void main(String[] args) {
        System.out.println(special("xyyx"));    // Output: 2
        System.out.println(special("aabbaa"));  // Output: 4
        System.out.println(special("pq"));      // Output: 0
    }
}
My code runs in time complexity of O(n^2 * m) where n is the input word length and m is the substring string length. I am looking for an algorithm that takes less than O(n^2)
I need help in finding a way to solve this in less time complexity.

The rules don't require that the middle letters differ from the start/end letters.This is correct. \$\endgroup\$