Sponsored
Sponsored
The two pointers approach uses two indices to represent the start and end of the string. The idea is to check for matching characters from both ends and shrink the string until the characters differ. Loop through the string, adjusting these pointers to remove any prefixes and suffixes with matching characters. This method is efficient as it only requires a single pass through the string.
Time Complexity: O(n), where n is the length of the string, because each character is visited at most twice.
Space Complexity: O(1), as no additional space is used apart from variables.
1using System;
2
3public class Solution {
4 public int MinimumLength(string s) {
5 int left = 0, right = s.Length - 1;
6 while (left < right && s[left] == s[right]) {
7 char currentChar = s[left];
8 while (left <= right && s[left] == currentChar) {
9 left++;
10 }
11 while (left <= right && s[right] == currentChar) {
12 right--;
13 }
14 }
15 return right - left + 1;
16 }
17
18 public static void Main(string[] args) {
19 Solution solution = new Solution();
20 Console.WriteLine(solution.MinimumLength("aabccabba")); // Output: 3
21 }
22}
This C# method employs a double-pointer strategy to analyze and minimize the string by removing characters symmetrically when the same character appears at both ends.
This recursive approach tries to minimize the string length by removing valid prefixes and suffixes. The base case is when no more valid removals are possible, and the remaining string length is minimal. Each recursive call attempts to strip away the symmetric ends and proceeds with the interior until the results match.
Time Complexity: O(n), since it navigates through the string at minimal overhead.
Space Complexity: O(n) due to recursion depth management.
public class Solution {
private int RecursiveLength(string s, int left, int right) {
if (left >= right) return right - left + 1;
if (s[left] != s[right]) return right - left + 1;
char currentChar = s[left];
while (left <= right && s[left] == currentChar) {
left++;
}
while (left <= right && s[right] == currentChar) {
right--;
}
return RecursiveLength(s, left, right);
}
public int MinimumLength(string s) {
return RecursiveLength(s, 0, s.Length - 1);
}
public static void Main(string[] args) {
Solution solution = new Solution();
Console.WriteLine(solution.MinimumLength("aabccabba")); // Output: 3
}
}
Through the C# recursive manner, RecursiveLength
examines string edges, methodically excising character pairs when homogeneous. Recursive invocations holistically reduce visible string sizes as expected.