将一个字符串转换为另一个字符串所需的最小给定操作数
给定两个长度相等的字符串S和T。两个字符串都只包含字符'0'和'1' 。任务是找到将字符串S转换为T的最小操作数。字符串S允许两种类型的操作:
- 交换字符串的任意两个字符。
- 用“1”替换“0” ,反之亦然。
例子:
Input: S = “011”, T = “101”
Output: 1
Swap the first and second character.
Input: S = “010”, T = “101”
Output: 2
Swap the first and second character and replace the third character with ‘1’.
方法:为字符串S找到 2 个值,具有 0 但应为 1 的索引数以及具有 1 但应为 0 的索引数。结果将是这两个值的最大值,因为我们可以使用交换这两个值中的最小值和剩余的不匹配字符可以反转,即'0'可以更改为'1'并且'1'可以更改为'0' 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the minimum operations
// of the given type required to convert
// string s to string t
int minOperations(string s, string t, int n)
{
int ct0 = 0, ct1 = 0;
for (int i = 0; i < n; i++) {
// Characters are already equal
if (s[i] == t[i])
continue;
// Increment count of 0s
if (s[i] == '0')
ct0++;
// Increment count of 1s
else
ct1++;
}
return max(ct0, ct1);
}
// Driver code
int main()
{
string s = "010", t = "101";
int n = s.length();
cout << minOperations(s, t, n);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function to return the minimum
// operations of the given type required
// to convert string s to string t
static int minOperations(String s,
String t, int n)
{
int ct0 = 0, ct1 = 0;
for (int i = 0; i < n; i++)
{
// Characters are already equal
if (s.charAt(i) == t.charAt(i))
continue;
// Increment count of 0s
if (s.charAt(i) == '0')
ct0++;
// Increment count of 1s
else
ct1++;
}
return Math.max(ct0, ct1);
}
// Driver code
public static void main(String args[])
{
String s = "010", t = "101";
int n = s.length();
System.out.println(minOperations(s, t, n));
}
}
// This code is contributed by
// Surendra_Gangwar
Python3
# Python 3 implementation of the approach
# Function to return the minimum operations
# of the given type required to convert
# string s to string t
def minOperations(s, t, n):
ct0 = 0
ct1 = 0
for i in range(n):
# Characters are already equal
if (s[i] == t[i]):
continue
# Increment count of 0s
if (s[i] == '0'):
ct0 += 1
# Increment count of 1s
else:
ct1 += 1
return max(ct0, ct1)
# Driver code
if __name__ == "__main__":
s = "010"
t = "101"
n = len(s)
print(minOperations(s, t, n))
# This code is contributed by ita_c
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the minimum operations
// of the given type required to convert
// string s to string t
static int minOperations(string s,
string t, int n)
{
int ct0 = 0, ct1 = 0;
for (int i = 0; i < n; i++)
{
// Characters are already equal
if (s[i] == t[i])
continue;
// Increment count of 0s
if (s[i] == '0')
ct0++;
// Increment count of 1s
else
ct1++;
}
return Math.Max(ct0, ct1);
}
// Driver code
public static void Main()
{
string s = "010", t = "101";
int n = s.Length;
Console.Write(minOperations(s, t, n));
}
}
// This code is contributed
// by Akanksha Rai
PHP
Javascript
输出:
2
时间复杂度: O(N)