给定一个字符串str 。任务是计算要删除的最小元素数,以使成对的连续元素相同
例子:
Input : str = “11344”
Output: 1
Remove the digit 3 from 3rd place so that the string becomes 1144. Thus pairwise two consecutive elements are same. Hence answer is 1.
Input : str = “55553”
Output : 1
Remove the digit 3 from the 5th place so that the string becomes 5555. Thus pairwise two consecutive elements are same. Hence answer is 1.
方法:检查当前两个连续的元素是否相同。如果是,则将索引增加2并继续检查,直到遍历所有元素。否则将索引增加1并以1计数。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to count the minimum number of elements
// to remove from a number so that pairwise two
// consecutive digits are same.
int countConsecutive(string s)
{
// initialize counting variable
int count = 0;
for (int i = 0; i < s.size(); i++) {
// check if two consecutive digits are same
if (s[i] == s[i + 1])
i++;
else
count++;
}
return count;
}
// Driver code
int main()
{
string str = "44522255";
cout << countConsecutive(str);
return 0;
}
Java
// Java implementation of the above approach
class GFG {
// Function to count the minimum number of elements
// to remove from a number so that pairwise two
// consecutive digits are same.
static int countConsecutive(String s) {
// initialize counting variable
int count = 0;
for (int i = 0; i < s.length(); i++) {
// check if two consecutive digits are same
if (s.charAt(i) == s.charAt(i + 1)) {
i++;
} else {
count++;
}
}
return count;
}
// Driver code
public static void main(String args[]) {
String str = "44522255";
System.out.println(countConsecutive(str));
}
}
// This code is contributed by PrinciRaj19992
Python3
# Python 3 implementation of the above approach
# Function to count the minimum number of
# elements to remove from a number so that
# pairwise two consecutive digits are same.
def countConsecutive(s):
# initialize counting variable
count = -1
for i in range(len(s)-1):
# check if two consecutive
# digits are same
if(i <= len(s)):
if (s[i] is s[i + 1]):
i += 1
else:
count += 1
return count
# Driver code
if __name__ == '__main__':
str = "44522255"
print(countConsecutive(str))
# This code is contributed by PrinciRaj1992
C#
// C# implementation of above approach
using System;
public class GFG {
// Function to count the minimum number of elements
// to remove from a number so that pairwise two
// consecutive digits are same.
static int countConsecutive(String s) {
// initialize counting variable
int count = 0;
for (int i = 0; i < s.Length; i++) {
// check if two consecutive digits are same
if (s[i] == s[i+1]) {
i++;
} else {
count++;
}
}
return count;
}
// Driver code
public static void Main() {
String str = "44522255";
Console.WriteLine(countConsecutive(str));
}
}
// This code is contributed by 29AjayKumar
PHP
Javascript
输出:
2
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。