检查给定的字符串是否由两个交替的字符组成
给定一个字符串str ,任务是检查给定字符串是否仅由两个交替字符组成。
例子:
Input: str = “ABABABAB”
Output: Yes
Input: str = “XYZ”
Output: No
方法:为了使字符串仅由两个交替字符组成,它必须满足以下条件:
- 奇数索引处的所有字符必须相同。
- 偶数索引处的所有字符必须相同。
- str[0] != str[1] (这是因为单个字符重复多次的“AAAAA”类型的字符串也将满足上述两个条件)
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function that returns true if the string
// is made up of two alternating characters
bool isTwoAlter(string s)
{
// Check if ith character matches
// with the character at index (i + 2)
for (int i = 0; i < s.length() - 2; i++) {
if (s[i] != s[i + 2]) {
return false;
}
}
// If string consists of a single
// character repeating itself
if (s[0] == s[1])
return false;
return true;
}
// Driver code
int main()
{
string str = "ABAB";
if (isTwoAlter(str))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG
{
// Function that returns true if the string
// is made up of two alternating characters
static boolean isTwoAlter(String s)
{
// Check if ith character matches
// with the character at index (i + 2)
for (int i = 0; i < s.length() - 2; i++)
{
if (s.charAt(i) != s.charAt(i + 2))
{
return false;
}
}
// If string consists of a single
// character repeating itself
if (s.charAt(0) == s.charAt(1))
return false;
return true;
}
// Driver code
public static void main (String[] args)
{
String str = "ABAB";
if (isTwoAlter(str))
System.out.print( "Yes");
else
System.out.print("No");
}
}
// This code is contributed by anuj_67..
Python 3
# Function that returns true if the string
# is made up of two alternating characters
def isTwoAlter( s):
# Check if ith character matches
# with the character at index (i + 2)
for i in range ( len( s) - 2) :
if (s[i] != s[i + 2]) :
return False
#If string consists of a single
#character repeating itself
if (s[0] == s[1]):
return False
return True
# Driver code
if __name__ == "__main__":
str = "ABAB"
if (isTwoAlter(str)):
print ( "Yes")
else:
print ("No")
# This code is contributed by ChitraNayal
C#
// C# implementation of the approach
using System;
class GFG
{
// Function that returns true if the string
// is made up of two alternating characters
static bool isTwoAlter(string s)
{
// Check if ith character matches
// with the character at index (i + 2)
for (int i = 0; i < s.Length - 2; i++)
{
if (s[i] != s[i +2])
{
return false;
}
}
// If string consists of a single
// character repeating itself
if (s[0] == s[1])
return false;
return true;
}
// Driver code
public static void Main()
{
string str = "ABAB";
if (isTwoAlter(str))
Console.WriteLine( "Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by AnkitRai01
Javascript
输出:
Yes
时间复杂度:O(N)
辅助空间:O(1)