java.lang.Object
g2501_2600.s2516_take_k_of_each_character_from_left_and_right.Solution

public class Solution extends Object
2516 - Take K of Each Character From Left and Right.<p>Medium</p> <p>You are given a string <code>s</code> consisting of the characters <code>'a'</code>, <code>'b'</code>, and <code>'c'</code> and a non-negative integer <code>k</code>. Each minute, you may take either the <strong>leftmost</strong> character of <code>s</code>, or the <strong>rightmost</strong> character of <code>s</code>.</p> <p>Return <em>the <strong>minimum</strong> number of minutes needed for you to take <strong>at least</strong></em> <code>k</code> <em>of each character, or return</em> <code>-1</code> <em>if it is not possible to take</em> <code>k</code> <em>of each character.</em></p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> s = &ldquo;aabaaaacaabc&rdquo;, k = 2</p> <p><strong>Output:</strong> 8</p> <p><strong>Explanation:</strong></p> <p>Take three characters from the left of s. You now have two &lsquo;a&rsquo; characters, and one &lsquo;b&rsquo; character.</p> <p>Take five characters from the right of s. You now have four &lsquo;a&rsquo; characters, two &lsquo;b&rsquo; characters, and two &lsquo;c&rsquo; characters.</p> <p>A total of 3 + 5 = 8 minutes is needed.</p> <p>It can be proven that 8 is the minimum number of minutes needed.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> s = &ldquo;a&rdquo;, k = 1</p> <p><strong>Output:</strong> -1</p> <p><strong>Explanation:</strong> It is not possible to take one &lsquo;b&rsquo; or &lsquo;c&rsquo; so return -1.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= s.length <= 10<sup>5</sup></code></li> <li><code>s</code> consists of only the letters <code>'a'</code>, <code>'b'</code>, and <code>'c'</code>.</li> <li><code>0 <= k <= s.length</code></li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • takeCharacters

      public int takeCharacters(String s, int k)