1864:构成交替字符串需要的最小交换次数

This commit is contained in:
huangge1199 2021-06-07 13:09:24 +08:00
parent cf16165f02
commit 73d80b1da7
2 changed files with 122 additions and 0 deletions

View File

@ -0,0 +1,82 @@
//给你一个二进制字符串 s 现需要将其转化为一个 交替字符串 请你计算并返回转化所需的 最小 字符交换次数如果无法完成转化返回 -1
//
// 交替字符串 是指相邻字符之间不存在相等情况的字符串例如字符串 "010" "1010" 属于交替字符串 "0100" 不是
//
// 任意两个字符都可以进行交换不必相邻
//
//
//
// 示例 1
//
//
//输入s = "111000"
//输出1
//解释交换位置 1 4"111000" -> "101010" 字符串变为交替字符串
//
//
// 示例 2
//
//
//输入s = "010"
//输出0
//解释字符串已经是交替字符串了不需要交换
//
//
// 示例 3
//
//
//输入s = "1110"
//输出-1
//
//
//
//
// 提示
//
//
// 1 <= s.length <= 1000
// s[i] 的值为 '0' '1'
//
// Related Topics 贪心算法
// 👍 8 👎 0
package leetcode.editor.cn;
//1864:构成交替字符串需要的最小交换次数
public class MinimumNumberOfSwapsToMakeTheBinaryStringAlternating{
public static void main(String[] args) {
//测试代码
Solution solution = new MinimumNumberOfSwapsToMakeTheBinaryStringAlternating().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int minSwaps(String s) {
int s0 = s.replace("0", "").length();
int s1 = s.replace("1", "").length();
if (Math.abs(s0 - s1) > 1) {
return -1;
}
int com = 0;
int m0 = 0;
for (int i = 0; i < s.length(); i++) {
if (com != s.charAt(i) - '0') {
m0++;
}
com = 1 - com;
}
m0 = m0 % 2 == 0 ? m0 : Integer.MAX_VALUE;
com = 1;
int m1 = 0;
for (int i = 0; i < s.length(); i++) {
if (com != s.charAt(i) - '0') {
m1++;
}
com = 1 - com;
}
m1 = m1 % 2 == 0 ? m1 : Integer.MAX_VALUE;
return Math.min(m0, m1) / 2;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,40 @@
<p>给你一个二进制字符串 <code>s</code> ,现需要将其转化为一个 <strong>交替字符串</strong> 。请你计算并返回转化所需的 <strong>最小</strong> 字符交换次数,如果无法完成转化,返回<em> </em><code>-1</code><em> </em></p>
<p><strong>交替字符串</strong> 是指:相邻字符之间不存在相等情况的字符串。例如,字符串 <code>"010"</code><code>"1010"</code> 属于交替字符串,但 <code>"0100"</code> 不是。</p>
<p>任意两个字符都可以进行交换,<strong>不必相邻</strong></p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>s = "111000"
<strong>输出:</strong>1
<strong>解释:</strong>交换位置 1 和 4"1<em><strong>1</strong></em>10<em><strong>0</strong></em>0" -> "1<em><strong>0</strong></em>10<em><strong>1</strong></em>0" ,字符串变为交替字符串。
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>s = "010"
<strong>输出:</strong>0
<strong>解释:</strong>字符串已经是交替字符串了,不需要交换。
</pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入:</strong>s = "1110"
<strong>输出:</strong>-1
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= s.length <= 1000</code></li>
<li><code>s[i]</code> 的值为 <code>'0'</code><code>'1'</code></li>
</ul>
<div><div>Related Topics</div><div><li>贪心算法</li></div></div>\n<div><li>👍 8</li><li>👎 0</li></div>