给定一个字符串,检查给定字符串的字符可以重新排列成回文。
例如“geeksogeeks”的字符可以重新排列形成回文“geeksoskeeg”,但“geeksforgeeks”的字符不能重新排列形成回文。
如果最多一个字符出现奇数次并且所有字符出现偶数次,则一组字符可以形成回文。
一个简单的解决方案是运行两个循环,外循环一个一个选择所有字符,内循环计算所选择字符的出现次数。我们跟踪奇数。该解决方案的时间复杂度为 O(n 2 )。
我们可以使用计数数组在 O(n) 时间内完成。以下是详细步骤。
- 创建一个字母大小的计数数组,通常为 256。将计数数组的所有值初始化为 0。
- 遍历给定的字符串并增加每个字符的计数。
- 遍历计数数组,如果计数数组有多个奇数,则返回false。否则,返回真。
下面是上述方法的实现。
C++
// C++ implementation to check if
// characters of a given string can
// be rearranged to form a palindrome
#include
using namespace std;
#define NO_OF_CHARS 256
/* function to check whether
characters of a string can form a palindrome */
bool canFormPalindrome(string str)
{
// Create a count array and initialize all
// values as 0
int count[NO_OF_CHARS] = { 0 };
// For each character in input strings,
// increment count in the corresponding
// count array
for (int i = 0; str[i]; i++)
count[str[i]]++;
// Count odd occurring characters
int odd = 0;
for (int i = 0; i < NO_OF_CHARS; i++) {
if (count[i] & 1)
odd++;
if (odd > 1)
return false;
}
// Return true if odd count is 0 or 1,
return true;
}
/* Driver code*/
int main()
{
canFormPalindrome("geeksforgeeks")
? cout << "Yes\n"
: cout << "No\n";
canFormPalindrome("geeksogeeks")
? cout << "Yes\n"
: cout << "No\n";
return 0;
}
Java
// Java implementation to check if
// characters of a given string can
// be rearranged to form a palindrome
import java.io.*;
import java.math.*;
import java.util.*;
class GFG {
static int NO_OF_CHARS = 256;
/* function to check whether characters
of a string can form a palindrome */
static boolean canFormPalindrome(String str)
{
// Create a count array and initialize all
// values as 0
int count[] = new int[NO_OF_CHARS];
Arrays.fill(count, 0);
// For each character in input strings,
// increment count in the corresponding
// count array
for (int i = 0; i < str.length(); i++)
count[(int)(str.charAt(i))]++;
// Count odd occurring characters
int odd = 0;
for (int i = 0; i < NO_OF_CHARS; i++) {
if ((count[i] & 1) == 1)
odd++;
if (odd > 1)
return false;
}
// Return true if odd count is 0 or 1,
return true;
}
// Driver code
public static void main(String args[])
{
if (canFormPalindrome("geeksforgeeks"))
System.out.println("Yes");
else
System.out.println("No");
if (canFormPalindrome("geeksogeeks"))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Nikita Tiwari.
Python
# Python3 implementation to check if
# characters of a given string can
# be rearranged to form a palindrome
NO_OF_CHARS = 256
# function to check whether characters
# of a string can form a palindrome
def canFormPalindrome(st):
# Create a count array and initialize
# all values as 0
count = [0] * (NO_OF_CHARS)
# For each character in input strings,
# increment count in the corresponding
# count array
for i in range(0, len(st)):
count[ord(st[i])] = count[ord(st[i])] + 1
# Count odd occurring characters
odd = 0
for i in range(0, NO_OF_CHARS):
if (count[i] & 1):
odd = odd + 1
if (odd > 1):
return False
# Return true if odd count is 0 or 1,
return True
# Driver code
if(canFormPalindrome("geeksforgeeks")):
print("Yes")
else:
print("No")
if(canFormPalindrome("geeksogeeks")):
print("Yes")
else:
print("No")
# This code is contributed by Nikita Tiwari.
C#
// C# implementation to check if
// characters of a given string can
// be rearranged to form a palindrome
using System;
class GFG {
static int NO_OF_CHARS = 256;
/* function to check whether characters
of a string can form a palindrome */
static bool canFormPalindrome(string str)
{
// Create a count array and initialize all
// values as 0
int[] count = new int[NO_OF_CHARS];
Array.Fill(count, 0);
// For each character in input strings,
// increment count in the corresponding
// count array
for (int i = 0; i < str.Length; i++)
count[(int)(str[i])]++;
// Count odd occurring characters
int odd = 0;
for (int i = 0; i < NO_OF_CHARS; i++) {
if ((count[i] & 1) == 1)
odd++;
if (odd > 1)
return false;
}
// Return true if odd count is 0 or 1,
return true;
}
// Driver code
public static void Main()
{
if (canFormPalindrome("geeksforgeeks"))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
if (canFormPalindrome("geeksogeeks"))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
Javascript
C++
#include
using namespace std;
/*
* function to check whether characters of
a string can form a palindrome
*/
bool canFormPalindrome(string str)
{
// Create a list
vector list;
// For each character in input strings,
// remove character if list contains
// else add character to list
for (int i = 0; i < str.length(); i++)
{
auto pos = find(list.begin(),
list.end(), str[i]);
if (pos != list.end()) {
auto posi
= find(list.begin(),
list.end(), str[i]);
list.erase(posi);
}
else
list.push_back(str[i]);
}
// if character length is even list is
// expected to be empty or if character
// length is odd list size is expected to be 1
// if string length is even
if (str.length() % 2 == 0
&& list.empty()
|| (str.length() % 2 == 1
&& list.size() == 1))
return true;
// if string length is odd
else
return false;
}
// Driver code
int main()
{
if (canFormPalindrome("geeksforgeeks"))
cout << ("Yes") << endl;
else
cout << ("No") << endl;
if (canFormPalindrome("geeksogeeks"))
cout << ("Yes") << endl;
else
cout << ("No") << endl;
}
// This code is contributed by Rajput-Ji
Java
import java.util.ArrayList;
import java.util.List;
class GFG {
/*
* function to check whether
* characters of a string can form a palindrome
*/
static boolean canFormPalindrome(String str)
{
// Create a list
List list = new ArrayList();
// For each character in input strings,
// remove character if list contains
// else add character to list
for (int i = 0; i < str.length(); i++)
{
if (list.contains(str.charAt(i)))
list.remove((Character)str.charAt(i));
else
list.add(str.charAt(i));
}
// if character length is even
// list is expected to be empty or
// if character length is odd list size
// is expected to be 1
// if string length is even
if (str.length() % 2 == 0
&& list.isEmpty()
|| (str.length() % 2 == 1
&& list.size()
== 1))
return true;
// if string length is odd
else
return false;
}
// Driver code
public static void main(String args[])
{
if (canFormPalindrome("geeksforgeeks"))
System.out.println("Yes");
else
System.out.println("No");
if (canFormPalindrome("geeksogeeks"))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Sugunakumar P
Python
'''
* function to check whether characters of
a string can form a palindrome
'''
def canFormPalindrome(strr):
# Create a listt
listt = []
# For each character in input strings,
# remove character if listt contains
# else add character to listt
for i in range(len(strr)):
if (strr[i] in listt):
listt.remove(strr[i])
else:
listt.append(strr[i])
# if character length is even
# list is expected to be empty
# or if character length is odd
# listt size is expected to be 1
if (len(strr) % 2 == 0 and len(listt) == 0 or
(len(strr) % 2 == 1 and len(listt) == 1)):
return True
else:
return False
# Driver code
if (canFormPalindrome("geeksforgeeks")):
print("Yes")
else:
print("No")
if (canFormPalindrome("geeksogeeks")):
print("Yes")
else:
print("No")
# This code is contributed by SHUBHAMSINGH10
C#
// C# Implementation of the above approach
using System;
using System.Collections.Generic;
class GFG {
/*
* function to check whether characters
of a string can form a palindrome
*/
static Boolean canFormPalindrome(String str)
{
// Create a list
List list = new List();
// For each character in input strings,
// remove character if list contains
// else add character to list
for (int i = 0; i < str.Length; i++)
{
if (list.Contains(str[i]))
list.Remove((char)str[i]);
else
list.Add(str[i]);
}
// if character length is even
// list is expected to be empty
// or if character length is odd
// list size is expected to be 1
// if string length is even
if (str.Length % 2 == 0 && list.Count == 0
||
(str.Length % 2 == 1
&& list.Count == 1))
return true;
// if string length is odd
else
return false;
}
// Driver Code
public static void Main(String[] args)
{
if (canFormPalindrome("geeksforgeeks"))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
if (canFormPalindrome("geeksogeeks"))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by Rajput-Ji
Javascript
C++
// C++ Implementation of the above approach
# include
using namespace std;
bool canFormPalindrome(string a)
{
// bitvector to store
// the record of which character appear
// odd and even number of times
int bitvector = 0, mask = 0;
for (int i=0; a[i] != '\0'; i++)
{
int x = a[i] - 'a';
mask = 1 << x;
bitvector = bitvector ^ mask;
}
return (bitvector & (bitvector - 1)) == 0;
}
// Driver Code
int main()
{
if (canFormPalindrome("geeksforgeeks"))
cout << ("Yes") << endl;
else
cout << ("No") << endl;
return 0;
}
Java
// Java Implementation of the above approach
import java.io.*;
class GFG
{
static boolean canFormPalindrome(String a)
{
// bitvector to store
// the record of which character appear
// odd and even number of times
int bitvector = 0, mask = 0;
for (int i = 0; i < a.length(); i++)
{
int x = a.charAt(i) - 'a';
mask = 1 << x;
bitvector = bitvector ^ mask;
}
return (bitvector & (bitvector - 1)) == 0;
}
// Driver Code
public static void main (String[] args) {
if (canFormPalindrome("geeksforgeeks"))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by rag2127
Python3
# Python3 implementation of above approach.
def canFormPalindrome(s):
bitvector = 0
for str in s:
bitvector ^= 1 << ord(str)
return bitvector == 0 or bitvector & (bitvector - 1) == 0
#s = input()
if canFormPalindrome("geeksforgeeks"):
print('Yes')
else:
print('No')
# This code is contributed by sahilmahale0
C#
// C# Implementation of the above approach
using System;
public class GFG
{
static bool canFormPalindrome(string a)
{
// bitvector to store
// the record of which character appear
// odd and even number of times
int bitvector = 0, mask = 0;
for (int i = 0; i < a.Length; i++)
{
int x = a[i] - 'a';
mask = 1 << x;
bitvector = bitvector ^ mask;
}
return (bitvector & (bitvector - 1)) == 0;
}
// Driver Code
static public void Main (){
if (canFormPalindrome("geeksforgeeks"))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by avanitrachhadiya2155
Javascript
输出
No
Yes
另一种方法:
我们可以使用列表在 O(n) 时间内完成。以下是详细步骤。
- 创建字符列表。
- 遍历给定的字符串。
- 对于字符串中的每个字符,如果列表已经包含,则删除该字符,否则将其添加到列表中。
- 如果字符串长度是偶数,则列表应为空。
- 或者,如果字符串长度为奇数,则列表大小预计为 1
- 以上两个条件(3)或(4)返回真,否则返回假。
C++
#include
using namespace std;
/*
* function to check whether characters of
a string can form a palindrome
*/
bool canFormPalindrome(string str)
{
// Create a list
vector list;
// For each character in input strings,
// remove character if list contains
// else add character to list
for (int i = 0; i < str.length(); i++)
{
auto pos = find(list.begin(),
list.end(), str[i]);
if (pos != list.end()) {
auto posi
= find(list.begin(),
list.end(), str[i]);
list.erase(posi);
}
else
list.push_back(str[i]);
}
// if character length is even list is
// expected to be empty or if character
// length is odd list size is expected to be 1
// if string length is even
if (str.length() % 2 == 0
&& list.empty()
|| (str.length() % 2 == 1
&& list.size() == 1))
return true;
// if string length is odd
else
return false;
}
// Driver code
int main()
{
if (canFormPalindrome("geeksforgeeks"))
cout << ("Yes") << endl;
else
cout << ("No") << endl;
if (canFormPalindrome("geeksogeeks"))
cout << ("Yes") << endl;
else
cout << ("No") << endl;
}
// This code is contributed by Rajput-Ji
Java
import java.util.ArrayList;
import java.util.List;
class GFG {
/*
* function to check whether
* characters of a string can form a palindrome
*/
static boolean canFormPalindrome(String str)
{
// Create a list
List list = new ArrayList();
// For each character in input strings,
// remove character if list contains
// else add character to list
for (int i = 0; i < str.length(); i++)
{
if (list.contains(str.charAt(i)))
list.remove((Character)str.charAt(i));
else
list.add(str.charAt(i));
}
// if character length is even
// list is expected to be empty or
// if character length is odd list size
// is expected to be 1
// if string length is even
if (str.length() % 2 == 0
&& list.isEmpty()
|| (str.length() % 2 == 1
&& list.size()
== 1))
return true;
// if string length is odd
else
return false;
}
// Driver code
public static void main(String args[])
{
if (canFormPalindrome("geeksforgeeks"))
System.out.println("Yes");
else
System.out.println("No");
if (canFormPalindrome("geeksogeeks"))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Sugunakumar P
Python
'''
* function to check whether characters of
a string can form a palindrome
'''
def canFormPalindrome(strr):
# Create a listt
listt = []
# For each character in input strings,
# remove character if listt contains
# else add character to listt
for i in range(len(strr)):
if (strr[i] in listt):
listt.remove(strr[i])
else:
listt.append(strr[i])
# if character length is even
# list is expected to be empty
# or if character length is odd
# listt size is expected to be 1
if (len(strr) % 2 == 0 and len(listt) == 0 or
(len(strr) % 2 == 1 and len(listt) == 1)):
return True
else:
return False
# Driver code
if (canFormPalindrome("geeksforgeeks")):
print("Yes")
else:
print("No")
if (canFormPalindrome("geeksogeeks")):
print("Yes")
else:
print("No")
# This code is contributed by SHUBHAMSINGH10
C#
// C# Implementation of the above approach
using System;
using System.Collections.Generic;
class GFG {
/*
* function to check whether characters
of a string can form a palindrome
*/
static Boolean canFormPalindrome(String str)
{
// Create a list
List list = new List();
// For each character in input strings,
// remove character if list contains
// else add character to list
for (int i = 0; i < str.Length; i++)
{
if (list.Contains(str[i]))
list.Remove((char)str[i]);
else
list.Add(str[i]);
}
// if character length is even
// list is expected to be empty
// or if character length is odd
// list size is expected to be 1
// if string length is even
if (str.Length % 2 == 0 && list.Count == 0
||
(str.Length % 2 == 1
&& list.Count == 1))
return true;
// if string length is odd
else
return false;
}
// Driver Code
public static void Main(String[] args)
{
if (canFormPalindrome("geeksforgeeks"))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
if (canFormPalindrome("geeksogeeks"))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by Rajput-Ji
Javascript
输出
No
Yes
另一种方法:(使用位)
此问题可以在O(n)的时间,其中n是字符串和O(1)在空间中的字符数来解决。
该字符串是回文的所有字符应发生的次数为偶数,如果字符串是偶数长度的,并且如果字符串长度为奇数几乎一个字符出现一个奇数倍。不需要跟踪字符的计数,只要跟踪计数是奇数还是偶数就足够了。
这可以通过使用变量作为位向量来实现。
对于字符串的每个字符:
如果字符对应的位没有设置://如果是字符的奇数出现设置位
else if 对应于字符的位被设置: //如果是字符偶数出现切换位
这类似于在位向量和掩码之间执行 XOR 操作。
下面是上述方法的实现:
C++
// C++ Implementation of the above approach
# include
using namespace std;
bool canFormPalindrome(string a)
{
// bitvector to store
// the record of which character appear
// odd and even number of times
int bitvector = 0, mask = 0;
for (int i=0; a[i] != '\0'; i++)
{
int x = a[i] - 'a';
mask = 1 << x;
bitvector = bitvector ^ mask;
}
return (bitvector & (bitvector - 1)) == 0;
}
// Driver Code
int main()
{
if (canFormPalindrome("geeksforgeeks"))
cout << ("Yes") << endl;
else
cout << ("No") << endl;
return 0;
}
Java
// Java Implementation of the above approach
import java.io.*;
class GFG
{
static boolean canFormPalindrome(String a)
{
// bitvector to store
// the record of which character appear
// odd and even number of times
int bitvector = 0, mask = 0;
for (int i = 0; i < a.length(); i++)
{
int x = a.charAt(i) - 'a';
mask = 1 << x;
bitvector = bitvector ^ mask;
}
return (bitvector & (bitvector - 1)) == 0;
}
// Driver Code
public static void main (String[] args) {
if (canFormPalindrome("geeksforgeeks"))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by rag2127
蟒蛇3
# Python3 implementation of above approach.
def canFormPalindrome(s):
bitvector = 0
for str in s:
bitvector ^= 1 << ord(str)
return bitvector == 0 or bitvector & (bitvector - 1) == 0
#s = input()
if canFormPalindrome("geeksforgeeks"):
print('Yes')
else:
print('No')
# This code is contributed by sahilmahale0
C#
// C# Implementation of the above approach
using System;
public class GFG
{
static bool canFormPalindrome(string a)
{
// bitvector to store
// the record of which character appear
// odd and even number of times
int bitvector = 0, mask = 0;
for (int i = 0; i < a.Length; i++)
{
int x = a[i] - 'a';
mask = 1 << x;
bitvector = bitvector ^ mask;
}
return (bitvector & (bitvector - 1)) == 0;
}
// Driver Code
static public void Main (){
if (canFormPalindrome("geeksforgeeks"))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by avanitrachhadiya2155
Javascript
输出
No
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。