0% found this document useful (0 votes)
89 views38 pages

Coding

Uploaded by

seheranabia22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views38 pages

Coding

Uploaded by

seheranabia22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

#include <iostream>

using namespace std;

int fibonacci(int n) {
if (n <= 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
int n = 10; // Number of terms in the Fibonacci series you
want to print
cout << "Fibonacci series up to " << n << " terms: ";

for (int i = 0; i < n; i++) {


cout << fibonacci(i) << " ";
}
cout << endl;

return 0;
}

Coding

###Substring Match

def string_matching(big_string, sub_string):


index = big_string.find(sub_string)
return index # Returns -1 if not found, otherwise returns
the starting index

# Example usage
if __name__ == "__main__":
big_string = input("Enter the big string: ")
sub_string = input("Enter the substring: ")

result = string_matching(big_string, sub_string)

if result != -1:
print(f"Substring found at index: {result}")
else:
print("Substring not found.")

#generate prime number


#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
for (int i = 1; i <= 100; i++) {
if (isPrime(i)) {
cout << i << " ";
}
}
return 0;
}

/ C++ program to find factorial of given


number
#include <iostream>
using namespace std;

// Function to find factorial


// of given number
int factorial(int n)
{
if (n == 0 || n == 1)
return 1;
return n * factorial(n - 1);
}

// Driver code
int main()
{
int num = 5;
cout << "Factorial of " << num << " is " << factorial(num) << endl;
return 0;
}

##check if the string is plaindrome or not


#include <iostream>
#include <cstring>
using namespace std;

int main() {
char str[100];
int len;
bool flag = false;

cout << "Enter a string: ";


cin >> str;

len = strlen(str);

for(int i = 0; i < len / 2; i++) {


if(str[i] != str[len - i - 1]) {
flag = true;
break;
}
}

if(flag) {
cout << str << " is not a palindrome." << endl;
} else {
cout << str << " is a palindrome." << endl;
}

return 0;
}
####FIND Duplicates in array
\def find_duplicates(arr):
counts = {}
duplicates = []

for num in arr:


if num in counts:
counts[num] += 1
else:
counts[num] = 1

for num, count in [Link]():


if count > 1:
[Link](num)

return duplicates

# Example usage
arr = [1, 2, 3, 2, 4, 5, 1]
print("Duplicates:", find_duplicates(arr)) # Output: [1, 2]

###Remove Duplicates

def remove_duplicates_preserve_order(arr):
unique_elements = []
for num in arr:
if num not in unique_elements:
unique_elements.append(num)
return unique_elements

# Example usage
arr = [1, 2, 3, 2, 4, 5, 1]
print("Array without duplicates (order preserved):",
remove_duplicates_preserve_order(arr)) # Output: [1, 2, 3, 4,
5]

###Check if the number is palindrome or not


#include<iostream>
using namespace std;
int main()
{
int n,num,digit,rev=0;
cout<<"enter a num"<<endl;
cin>>num;
n=num;

do
{
digit=num%10;
rev=(rev*10)+digit;
num=num/10;
}
while(num!=0);

if(n==rev &&n>0)
cout<<"number is palindrom"<<endl;
else
cout<<"not palindrom"<<endl;
return 0;

1. Remove strings with a length less than a given value


python
Copy code
def filter_strings_by_length(strings,
min_length):
return [string for string in strings
if len(string) >= min_length]

# Example usage
strings = ["apple", "banana", "grape",
"kiwi"]
min_length = 6
result =
filter_strings_by_length(strings,
min_length)
print(result) # Output: ["banana"]

### Check if a string is an isogram

def is_isogram(word):
word = [Link]() # To handle case sensitivity
return len(word) == len(set(word))

# Example usage
print(is_isogram("Ambidextrously")) # Output: True
(Isogram)
print(is_isogram("Mississippi")) # Output: False (Not an
isogram)

####PRINT Fibonacci number 1 to 100


#include <iostream>
using namespace std;

int fibonacci(int n) {
if (n <= 0) return 0;
if (n == 1) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
int n = 100; // Number of terms in the Fibonacci series you
want to print
cout << "Fibonacci series up to " << n << " terms: ";

for (int i = 0; i <= n; i++) {


cout << fibonacci(i) << " ";
}
cout << endl;

return 0;
}

###Reverse a String
function reverseString(str) {
return [Link]("").reverse().join("");
}
// Example usage
const str = "Hello, World!";
[Link](reverseString(str)); // Output: "!dlroW ,olleH"

###3Count Vowel in string


#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int countVowels(const string &str) {


int count = 0;
for (char ch : str) {
ch = tolower(ch); // Convert to lowercase to handle
uppercase vowels
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++;
}
}
return count;
}

int main() {
string input;
cout << "Enter a string: ";
getline(cin, input); // To read the entire line of input
int vowelCount = countVowels(input);
cout << "Number of vowels: " << vowelCount << endl;

return 0;

###Count number of word in a string

#include <iostream>
using namespace std;

int main() {

// declaring string
string sentence = "Mary had a little lamb";
// initialising no of words to 0
int words = 0;
// store length of string in lenOfSentence
int lenOfSentence = [Link]();

// run for loop from i = 0 to i < lenOfSentence


// to iterate through each character of the string
for(int i = 0; i < lenOfSentence; i++)
{
// check if current character is a space
if(sentence[i] == ' ')
{
// if it is a space, increment word count
words++;
}

}
// at the end of the for loop, no. of spaces have been
// counted. Increment word count one more time to get
// no. of words
words = words + 1;

cout << "No. of words = " << words << endl;

###Longest word in a senetnce


#include <iostream>
#include <string>

using namespace std;

int findLongestWordLength(const string &str) {


int longestLength = 0;
int currentLength = 0;

for (char ch : str) {


if (ch == ' ') {
if (currentLength > longestLength) {
longestLength = currentLength;
}
currentLength = 0; // Reset length for the next word
} else {
currentLength++;
}
}
// Check the last word (in case the sentence doesn't end with
a space)
if (currentLength > longestLength) {
longestLength = currentLength;
}

return longestLength;
}

int main() {
string input;
cout << "Enter a sentence: ";
getline(cin, input); // Use getline to read the entire sentence

int longestWordLength = findLongestWordLength(input);


cout << "The length of the longest word is: " <<
longestWordLength << endl;
return 0;
}

1. Reverse a String

Problem: Write a function to reverse a given string.

Solution:

cpp
Copy code
#include <iostream>
#include <string>
using namespace std;

string reverseString(const string& str) {


string reversed = str;
int n = [Link]();
for (int i = 0; i < n / 2; ++i) {
swap(reversed[i], reversed[n - i - 1]);
}
return reversed;
}

int main() {
string str = "Hello, World!";
cout << "Reversed String: " << reverseString(str)
<< endl;
return 0;
}

3. Count Vowels and Consonants

Problem: Count the number of vowels and consonants in a string.

Solution:

cpp
Copy code
#include <iostream>
#include <string>
using namespace std;

void countVowelsConsonants(const string& str) {


int vowels = 0, consonants = 0;
for (char ch : str) {
ch = tolower(ch);
if (isalpha(ch)) {
if (ch == 'a' || ch == 'e' || ch ==
'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}
cout << "Vowels: " << vowels << ", Consonants:
" << consonants << endl;
}
int main() {
string str = "Hello, World!";
countVowelsConsonants(str);
return 0;
}

Permutations of a Given String

#include <iostream>
#include <string>
using namespace std;

string compressString(const string& str) {


if ([Link]()) return str; // Handle empty string case

string compressed; // To store the compressed result


int count = 1; // To count occurrences of each character

// Iterate through the string


for (size_t i = 1; i <= [Link](); ++i) {
// If current character is the same as the previous one,
increment the count
if (i < [Link]() && str[i] == str[i - 1]) {
count++;
} else {
// Append the character and its count to the
compressed string
compressed += str[i - 1]; // Add the character
compressed += to_string(count); // Add the count
count = 1; // Reset count for the next character
}
}

// Check if the compressed string is actually shorter than the


original
return [Link]() < [Link]() ? compressed : str;
}

int main() {
string str = "aaabbc";
cout << "Compressed String: " << compressString(str) <<
endl; // Output: a3b2c1
return 0;
}

Problem: Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring without repeating
characters.

Example

●​ Input: s = "abcabcbb"
●​ Output: 3​
Explanation: The answer is "abc", with a length of 3.
●​ Input: s = "bbbbb"
●​ Output: 1​
Explanation: The answer is "b", with a length of 1.
#include <iostream>
#include <string>
using namespace std;

int lengthOfLongestSubstring(string s) {
​ int lastIndex[256] = {0}; // Array to
store the last index of each character
​ int maxLength = 0;
​ int left = 0; // Left pointer of the
sliding window

​ for (int right = 0; right <


[Link](); right++) {
​ // Update the left pointer if the
character has been seen and is in the
current window
​ if (lastIndex[s[right]] > left) {
​ left = lastIndex[s[right]];
​ }

​ // Update the last seen index of


the character
​ lastIndex[s[right]] = right + 1; //
Store next position to maintain unique
constraint

​ // Calculate the maximum length of


the substring
​ maxLength = max(maxLength, right -
left + 1);
​ }

​ return maxLength;
}

int main() {
​ string input;
​ cout << "Enter a string: ";
​ cin >> input;

​ int result =
lengthOfLongestSubstring(input);
​ cout << "Length of the longest
substring without repeating characters: "
<< result << endl;

​ return 0;
}

Explanation of the Code


1.​Array Initialization:
○​ An array lastIndex of size 256 is initialized to zero.
This size is sufficient to cover all ASCII characters.
Each index of the array corresponds to a character, and
the value at that index will represent the last seen
position of that character.
2.​Sliding Window Technique:
○​ Two pointers are used: left (the start of the current
substring) and right (the end).
○​ We iterate through the string using the right pointer.
3.​Check for Repeats:
○​ If the last index of the current character (s[right]) is
greater than left, it indicates that the character has
appeared in the current window.
○​ We then update the left pointer to lastIndex[s[right]],
which gives the position just after the last occurrence
of the character.
4.​Update Last Seen Index:
○​ We update the last seen index for the character to right
+ 1. We use right + 1 because we want to mark the
position where the character would next appear to ensure
uniqueness.
5.​Calculate Maximum Length:
○​ After processing each character, we calculate the length
of the current substring and update maxLength.

#include <iostream>

#include <string>

using namespace std;

int lengthOfLongestSubstring(string s) {

​ int lastIndex[256] = {0}; // Array to store the last index of each character

​ int maxLength = 0;

​ int left = 0; // Left pointer of the sliding window

We start by defining the variables:

●​ lastIndex[256] = {0}: This array will store the last seen position
of each character. Initially, all values are set to 0, meaning no characters
have been seen.
●​ maxLength = 0: Stores the maximum length of any substring without
repeating characters found so far.
●​ left = 0: Marks the start of the "sliding window" — it will adjust as
we find repeating characters.

​ for (int right = 0; right < [Link](); right++) {

​ // Update the left pointer if the character has been seen and is in the
current window

​ if (lastIndex[s[right]] > left) {

​ left = lastIndex[s[right]];

​ }

Check for Repeating Character: When we encounter a character s[right]


that has been seen before (i.e., it has a lastIndex greater than left), we
know that this character is repeating within the current window defined by
left and right.

Adjust the left Pointer: If a repeating character is found, we slide the left
pointer to lastIndex[currentChar]. This removes the repeated character
from the window, so the substring starting at left and ending at right no
longer has duplicates.

​ // Update the last seen index of the character

​ lastIndex[s[right]] = right + 1; // Store next position to maintain unique


constraint

​ // Calculate the maximum length of the substring


​ maxLength = max(maxLength, right - left + 1);

​ }

Calculate the Length of the Current Window: The length of the current
substring is right - left + 1.

Update maxLength: We use max() to check if the current substring length is


greater than the previously stored maxLength. If it is, we update
maxLength.

​ return maxLength;

int main() {

​ string input;

​ cout << "Enter a string: ";

​ cin >> input;

​ int result = lengthOfLongestSubstring(input);

​ cout << "Length of the longest substring without repeating characters: "
<< result << endl;

​ return 0;

}
1.​ Check for Repeating Character:
○​ lastIndex['a'] is 0, which is not greater than left = 0,
meaning 'a' hasn’t been seen within the current window.
2.​ Update lastIndex:
○​ Set lastIndex['a'] = right + 1 = 1.
3.​ Update maxLength:
○​ Calculate maxLength = max(0, right - left + 1) =
max(0, 0 - 0 + 1) = 1.
4.​ Current substring: "a", maxLength = 1.

Step 2: right = 1, Character = 'b'

1.​ Check for Repeating Character:


○​ lastIndex['b'] is 0, which is not greater than left = 0, so
'b' hasn’t been seen in the current window.
2.​ Update lastIndex:
○​ Set lastIndex['b'] = right + 1 = 2.
3.​ Update maxLength:
○​ Calculate maxLength = max(1, right - left + 1) =
max(1, 1 - 0 + 1) = 2.
4.​ Current substring: "ab", maxLength = 2.

Step 3: right = 2, Character = 'c'

1.​ Check for Repeating Character:


○​ lastIndex['c'] is 0, which is not greater than left = 0, so
'c' hasn’t been seen in the current window.
2.​ Update lastIndex:
○​ Set lastIndex['c'] = right + 1 = 3.
3.​ Update maxLength:
○​ Calculate maxLength = max(2, right - left + 1) =
max(2, 2 - 0 + 1) = 3.
4.​ Current substring: "abc", maxLength = 3.

Step 4: right = 3, Character = 'a'

1.​ Check for Repeating Character:


○​ lastIndex['a'] is 1, which is greater than or equal to left
= 0. This means 'a' was last seen at index 0 in the current
substring, making it a repeating character.
2.​ Move left Pointer:
○​ Update left = lastIndex['a'] = 1 to skip the previous
occurrence of 'a'.
3.​ Update lastIndex:
○​ Set lastIndex['a'] = right + 1 = 4.
4.​ Update maxLength:
○​ Calculate maxLength = max(3, right - left + 1) =
max(3, 3 - 1 + 1) = 3.
5.​ Current substring: "bca", maxLength = 3.

CPP program to check if a string is Palindrome


#include<bits/stdc++.h>
using namespace std;

int main(){
string str;
cin>>str;
int len, i;
bool isPalindrome = true;
len = [Link]();
for(i=0; i<len/2; i++){
if(str[i] != str[len-1-i]){
isPalindrome = false;
break;
}
}
if(isPalindrome){
cout<<"Yes"<<endl;
} else {
cout<<"NO"<<endl;
}
return 0;
}

CPP program to check if a number is palindrome


#include<bits/stdc++.h>
using namespace std;

int main(){
int num;
cin>>num;
string str = to_string(num);
int len, i;
bool isPalindrome = true;
len = [Link]();
for(i=0; i<len/2; i++){
if(str[i] != str[len-1-i]){
isPalindrome = false;
break;
}
}
if(isPalindrome){
cout<<"Yes"<<endl;
} else {
cout<<"NO"<<endl;
}
return 0;
}
1. Bubble Sort
Bubble Sort repeatedly compares and swaps adjacent
elements if they are in the wrong order.
python

def bubble_sort(arr):
​ n = len(arr)
​ for i in range(n):
​ # Last i elements are already sorted
​ for j in range(0, n-i-1):
​ if arr[j] > arr[j+1]:
​ # Swap if the element found is greater than the next
element
​ arr[j], arr[j+1] = arr[j+1], arr[j]
​ return arr

# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
print("Sorted array:", bubble_sort(arr))

2. Selection Sort

Selection Sort finds the minimum element from the unsorted


part and places it at the beginning.
def selection_sort(arr):
​ n = len(arr)
​ for i in range(n):
​ min_index = i
​ for j in range(i+1, n):
​ if arr[j] < arr[min_index]:
​ min_index = j
​ arr[i], arr[min_index] = arr[min_index], arr[i]
​ return arr

# Example usage
arr = [64, 25, 12, 22, 11]
print("Sorted array:", selection_sort(arr))

3. Insertion Sort

Insertion Sort builds the sorted array one item at a time by


inserting elements into their correct positions.
def insertion_sort(arr):
​ for i in range(1, len(arr)):
​ key = arr[i]
​ j=i-1
​ while j >= 0 and arr[j] > key:
​ arr[j + 1] = arr[j]
​ j -= 1
​ arr[j + 1] = key
​ return arr

# Example usage
arr = [12, 11, 13, 5, 6]
print("Sorted array:", insertion_sort(arr))
4. Merge Sort

Merge Sort is a divide-and-conquer algorithm that splits the


array in half, recursively sorts each half, and then merges the
sorted halves.
def merge_sort(arr):
​ if len(arr) > 1:
​ mid = len(arr) // 2
​ left_half = arr[:mid]
​ right_half = arr[mid:]

​ merge_sort(left_half)
​ merge_sort(right_half)

​ i=j=k=0
​ while i < len(left_half) and j < len(right_half):
​ if left_half[i] < right_half[j]:
​ arr[k] = left_half[i]
​ i += 1
​ else:
​ arr[k] = right_half[j]
​ j += 1
​ k += 1

​ while i < len(left_half):


​ arr[k] = left_half[i]
​ i += 1
​ k += 1
​ while j < len(right_half):
​ arr[k] = right_half[j]
​ j += 1
​ k += 1
​ return arr

# Example usage
arr = [38, 27, 43, 3, 9, 82, 10]
print("Sorted array:", merge_sort(arr))

Here are a few popular sorting algorithms with code examples


in Python. Each example includes a brief explanation and a
code snippet to help you understand how they work.
1. Bubble Sort

Bubble Sort repeatedly compares and swaps adjacent


elements if they are in the wrong order.

python

def bubble_sort(arr):
n = len(arr)
for i in range(n):
# Last i elements are already sorted
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
# Swap if the element found is greater than the next
element
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr

# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
print("Sorted array:", bubble_sort(arr))

2. Selection Sort

Selection Sort finds the minimum element from the unsorted


part and places it at the beginning.

python

def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i+1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr

# Example usage
arr = [64, 25, 12, 22, 11]
print("Sorted array:", selection_sort(arr))

3. Insertion Sort
Insertion Sort builds the sorted array one item at a time by
inserting elements into their correct positions.

python

def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr

# Example usage
arr = [12, 11, 13, 5, 6]
print("Sorted array:", insertion_sort(arr))

4. Merge Sort

Merge Sort is a divide-and-conquer algorithm that splits the


array in half, recursively sorts each half, and then merges the
sorted halves.

python

def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]

merge_sort(left_half)
merge_sort(right_half)

i=j=k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1

while i < len(left_half):


arr[k] = left_half[i]
i += 1
k += 1

while j < len(right_half):


arr[k] = right_half[j]
j += 1
k += 1
return arr

# Example usage
arr = [38, 27, 43, 3, 9, 82, 10]
print("Sorted array:", merge_sort(arr))

5. Quick Sort

Quick Sort is another divide-and-conquer algorithm that


selects a pivot, partitions the array, and then recursively sorts
the partitions.

def quick_sort(arr):
​ if len(arr) <= 1:
​ return arr
​ pivot = arr[len(arr) // 2]
​ left = [x for x in arr if x < pivot]
​ middle = [x for x in arr if x == pivot]
​ right = [x for x in arr if x > pivot]
​ return quick_sort(left) + middle + quick_sort(right)

# Example usage
arr = [3, 6, 8, 10, 1, 2, 1]
print("Sorted array:", quick_sort(arr))
// Sort array of string in C++
#include<bits/stdc++.h>
using namespace std;
void bubblesort(vector<string>& arr){
int n = [Link]();
string temp;
for(int i=0; i<n-1; i++){
for(int j=0; j<n-i-1; j++){
if(arr[j+1]< arr[j]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;

}
}
}
}

int main(){
vector<string>words = {"banana", "apple", "grape", "berry"};

bubblesort(words);

for(int i=0; i<[Link](); i++){


cout<<words[i]<<",";
}
cout<<endl;
return 0;
}

ChatGPT
You said:
give string realted and all others c++ prioblem with solutiuon for problem solving
exam,which freequently come
ChatGPT said:
ChatGPT
Here's a list of common C++ string-related problems that often appear in

programming exams, along with their solutions. These problems focus on string

manipulation, searching, and transformations.

1. Reverse a String
Problem: Write a function to reverse a given string.

Solution:
cpp
Copy code

#include <iostream> #include <string> using namespace std; string

reverseString(const string& str) { string reversed = str; int n =

[Link](); for (int i = 0; i < n / 2; ++i) { swap(reversed[i],

reversed[n - i - 1]); } return reversed; } int main() { string str =

"Hello, World!"; cout << "Reversed String: " << reverseString(str) <<

endl; return 0; }

2. Check if a String is Palindrome


Problem: Check if the given string is a palindrome.

Solution:
cpp
Copy code

#include <iostream> #include <string> using namespace std; bool

isPalindrome(const string& str) { int n = [Link](); for (int i = 0;

i < n / 2; ++i) { if (str[i] != str[n - i - 1]) { return false; } }

return true; } int main() { string str = "madam"; cout <<

(isPalindrome(str) ? "Palindrome" : "Not a Palindrome") << endl; return

0; }
3. Count Vowels and Consonants
Problem: Count the number of vowels and consonants in a string.

Solution:
cpp
Copy code

#include <iostream> #include <string> using namespace std; void

countVowelsConsonants(const string& str) { int vowels = 0, consonants =

0; for (char ch : str) { ch = tolower(ch); if (isalpha(ch)) { if (ch ==

'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { vowels++; }

else { consonants++; } } } cout << "Vowels: " << vowels << ",

Consonants: " << consonants << endl; } int main() { string str =

"Hello, World!"; countVowelsConsonants(str); return 0; }

4. Find the First Non-Repeating Character


Problem: Find the first non-repeating character in a string.

Solution:
cpp
Copy code

#include <iostream> #include <string> #include <unordered_map> using

namespace std; char firstNonRepeatingChar(const string& str) {

unordered_map<char, int> charCount; for (char ch : str) {

charCount[ch]++; } for (char ch : str) { if (charCount[ch] == 1) {

return ch; } } return '\0'; // return null character if no non-repeating

character is found } int main() { string str = "swiss"; char result =

firstNonRepeatingChar(str); if (result) { cout << "First Non-Repeating

Character: " << result << endl; } else { cout << "No Non-Repeating

Character Found" << endl; } return 0; }


5. String Compression
Problem: Implement basic string compression using the counts of repeated

characters.

Solution:
cpp
Copy code

#include <iostream> #include <string> using namespace std; string

compressString(const string& str) { string compressed; int count = 1;

for (size_t i = 1; i <= [Link](); ++i) { if (i < [Link]() &&

str[i] == str[i - 1]) { count++; } else { compressed += str[i - 1];

compressed += to_string(count); count = 1; } } return

[Link]() < [Link]() ? compressed : str; } int main() {

string str = "aaabbc"; cout << "Compressed String: " <<

compressString(str) << endl; return 0; }

6. Remove All Duplicates from a String


Problem: Remove all duplicate characters from a string.

Solution:
cpp
Copy code

#include <iostream> #include <string> #include <unordered_set> using

namespace std; string removeDuplicates(const string& str) {

unordered_set<char> seen; string result; for (char ch : str) { if

([Link](ch) == [Link]()) { [Link](ch); result += ch; } }

return result; } int main() { string str = "programming"; cout <<

"String without duplicates: " << removeDuplicates(str) << endl; return

0; }
7. Find All Permutations of a String
Problem: Generate all permutations of a given string.

Solution:
cpp
Copy code

#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

void permute(string str, int l, int r)

{ if (l == r)

cout << str << endl;

} else {

for (int i = l; i <= r; i++) {

swap(str[l], str[i]);

permute(str, l + 1, r); swap(str[l], str[i]); // backtrack } } }

int main()

{ string str = "ABC";

permute(str, 0, [Link]() - 1); return 0; }

You might also like