Don't be ashamed of N^2 IV

If you look at the constraints for this problem, the length of the string is 1000. You can solve it in N^2 with a constant of 26, which means O(26N^2) which would mean 26,000,000 steps. That's totally feasible and you shouldn't be ashamed if it gets the job done - and fast enough. Code is down below, cheers, ACC.


You are given a string s consisting of lowercase English letters.

 of s is called balanced if all distinct characters in the substring appear the same number of times.

Return the length of the longest balanced substring of s.

 

Example 1:

Input: s = "abbac"

Output: 4

Explanation:

The longest balanced substring is "abba" because both distinct characters 'a' and 'b' each appear exactly 2 times.

Example 2:

Input: s = "zzabccy"

Output: 4

Explanation:

The longest balanced substring is "zabc" because the distinct characters 'z''a''b', and 'c' each appear exactly 1 time.​​​​​​​

Example 3:

Input: s = "aba"

Output: 2

Explanation:

​​​​​​​One of the longest balanced substrings is "ab" because both distinct characters 'a' and 'b' each appear exactly 1 time. Another longest balanced substring is "ba".

 

Constraints:

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters.

public int LongestBalanced(string s)
{
    int retVal = 0;
    for (int i = 0; i < s.Length; i++)
    {
        int[] frequency = new int[26];
        for (int j = i; j < s.Length; j++)
        {
            frequency[(int)(s[j] - 'a')]++;
            int anchor = frequency[(int)(s[j] - 'a')];
            bool found = true;
            for (int k = 0; k < frequency.Length; k++)
            {
                if (frequency[k] > 0 && frequency[k] != anchor)
                {
                    found = false;
                    break;
                }
            }
            if (found)
            {
                retVal = Math.Max(retVal, j - i + 1);
            }
        }
    }

    return retVal;
}

Comments

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Shortest Bridge – A BFS Story (with a Twist)

Classic Dynamic Programming IX