Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if both halves of the string have same set of characters in C#
Firstly, set the string to be checked.
string s = "timetime";
Now set two counters for two halves of the string.
int []one = new int[MAX_CHAR]; int []two = new int[MAX_CHAR];
Check for both the halves of the string.
for (int i = 0, j = l - 1; i < j; i++, j--) {
one[str[i] - 'a']++;
two[str[j] - 'a']++;
}
The following is the complete code to check whether both the halves of the string have same set of characters or not in C#.
Example
using System;
class Demo {
static int MAX_CHAR = 26;
static bool findSameCharacters(string str) {
int []one = new int[MAX_CHAR];
int []two = new int[MAX_CHAR];
int l = str.Length;
if (l == 1)
return true;
for (int i = 0, j = l - 1; i < j; i++, j--) {
one[str[i] - 'a']++;
two[str[j] - 'a']++;
}
for (int i = 0; i < MAX_CHAR; i++)
if (one[i] != two[i])
return false;
return true;
}
public static void Main() {
string str = "timetime";
if (findSameCharacters(str))
Console.Write("Yes: Two halves are same!");
else
Console.Write("No! Two halves are not same!");
}
}
Output
Yes: Two halves are same!
Advertisements