Topic Description
Implement an algorithm that determines whether all characters of a string are all different. Here we require that additional storage structures not be allowed to be used.
Given a string inistring, return a bool value, true to mean that all characters are different, and false to represent the same characters. Guarantees that the characters in the string are ASCII characters. The length of the string is less than or equal to 3000. Test sample: "Aeiou" returns: True "BarackObama" returns: False idea: solution 1: The use of hash table can achieve time complexity of O (n). Code implementation:
* * With the help of hash table
/bool Checkdifferent (string inistring) {
int length = Inistring.size ();
if (length < 2) return
true;
BOOL hash[256]{};
for (auto x:inistring)
{
if (!hash[x])
hash[x] = true;
else return
false;
return true;
}
Since the topic has been requested, no additional storage structure is allowed, then the solution 1 does not meet the requirements
Solution 2:The most straightforward approach is to iterate through each character to determine if there is a repetition. Time complexity for O (n*n) code implementation:
/* Loop traversal to find whether there are duplicate characters, time complexity of O (n*n)
Note: According to the principle of the drawer, simply cycle the first 257 characters can be * * *
bool Checkdifferent (string inistring) {
int Length = Inistring.size ();
if (length < 2) return
true;
for (int i = 0, i < length;i++) for
(int j = i+1 J < length;j++)
if (inistring[i] = = Inistring[j])
Retu RN false;
return true;
}
Solution 2:You can sort the string first, the time complexity can be done O (NLOGN), and then go through the string again, time complexity of O (n), to determine whether there are duplicate characters. Code implementation:
/* Based on the implementation of the order, time complexity of O (NLOGN)/
bool Checkdifferent (string inistring) {
int length = Inistring.size ();
if (length < 2) return
true;
Sort (Inistring.begin (), Inistring.end ());
for (int i = 0, i < length-1;i++)
if (inistring[i] = = inistring[i + 1]) return
false;
return true;
}
Solution 4:Using regular expressions to determine if there are duplicate strings
/* Use a regular expression implementation to include the header file #include <regex>*/
bool CheckDifferent4 (string inistring) {
//. * to match 0-any number of characters, (.) Represents a capturing group, and "\\1" represents a reverse reference, meaning "\\1" and "(.)" The values for both positions can be the same as the
regex reg (". *" (.) (. *\\1). * "); Return
!regex_match (inistring, Reg);
}