Skip to content

1156. Swap For Longest Repeated Character Substring 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  int maxRepOpt1(string text) {
    int ans = 0;
    vector<int> count(26);
    vector<pair<char, int>> groups{{text[0], 1}};

    for (const char c : text)
      ++count[c - 'a'];

    for (int i = 1; i < text.length(); ++i)
      if (text[i] == text[i - 1])
        ++groups[groups.size() - 1].second;
      else
        groups.emplace_back(text[i], 1);

    for (const auto& [c, length] : groups)
      ans = max(ans, min(length + 1, count[c - 'a']));

    for (int i = 1; i + 1 < groups.size(); ++i)
      if (groups[i - 1].first == groups[i + 1].first && groups[i].second == 1)
        ans = max(ans, min(groups[i - 1].second + groups[i + 1].second + 1,
                           count[groups[i - 1].first - 'a']));

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
  public int maxRepOpt1(String text) {
    int ans = 0;
    int[] count = new int[26];
    List<int[]> groups = new ArrayList<>();

    for (final char c : text.toCharArray())
      ++count[c - 'a'];

    groups.add(new int[] {text.charAt(0), 1});

    for (int i = 1; i < text.length(); ++i)
      if (text.charAt(i) == text.charAt(i - 1))
        ++groups.get(groups.size() - 1)[1];
      else
        groups.add(new int[] {text.charAt(i), 1});

    for (int[] group : groups)
      ans = Math.max(ans, Math.min(group[1] + 1, count[group[0] - 'a']));

    for (int i = 1; i + 1 < groups.size(); ++i)
      if (groups.get(i - 1)[0] == groups.get(i + 1)[0] && groups.get(i)[1] == 1)
        ans = Math.max(ans, Math.min(groups.get(i - 1)[1] + groups.get(i + 1)[1] + 1,
                                     count[groups.get(i - 1)[0] - 'a']));

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def maxRepOpt1(self, text: str) -> int:
    count = collections.Counter(text)
    groups = [[c, len(list(group))]
              for c, group in itertools.groupby(text)]
    ans = max(min(length + 1, count[c]) for c, length in groups)

    for i in range(1, len(groups) - 1):
      if groups[i - 1][0] == groups[i + 1][0] and groups[i][1] == 1:
        ans = max(
            ans,
            min(groups[i - 1][1] + groups[i + 1][1] + 1, count
                [groups[i - 1][0]]))

    return ans