How to get a substring by deleting minimum number of characters? - c++

In this question, we take 2 strings as input say s1 and s2.
Now, first we need to check if s2 is a subsequence of s1. If not, print no.
But if it is, we need to print the minimum number of characters to be deleted from s1 to get s2.
Eg- thistext text
Here, text can be directly found without deleting any characters so the answer is 0.
Eg- cutefriendship crisp
In this case, the answer is 9.
What I've done so far,
#include <bits/stdc++.h>
using namespace std;
int checkIfSub(string s1, string s2, int m, int n)
{
int j = 0;
for(int i = 0; i < m && j < n; i++)
if(s1[i] == s2[j])
j++;
if(j == n)
return 0;
else
return 1;
}
int check(string s1, string s2)
{
int count = 0; string s3;
if(checkIfSub(s1, s2, s1.length(), s2.length()) == 1 || s2.length() > s1.length())
{
cout << "NO\n"; return 0;
}
int j = 0;
for(int i = 0; i < s1.length(); i++)
{
if(s1[i] == s2[j])
{
s3[j] = s1[j];
j++; continue;
}
count++;
}
cout << "YES " << count << "\n";
return 0;
}
int main() {
string s1, s2;
cin >> s1 >> s2;
check(s1, s2);
return 0;
}
My code works well for the second example, but fails the first case.
(This was a question asked in some interview I read online.)

Try something like this:
#include <iostream>
#include <string>
using namespace std;
bool check(const string &s1, const string &s2, int &minToDelete)
{
minToDelete = 0;
bool anySubSeqFound = false;
if (s2.empty())
return false;
string::size_type first = 0;
while ((first = s1.find(s2[0], first)) != string::npos)
{
int numDeleted = 0;
bool isSubSeq = true;
string::size_type next = first + 1;
for(string::size_type j = 1; j < s2.size(); ++j)
{
string::size_type found = s1.find(s2[j], next);
if (found == string::npos)
{
isSubSeq = false;
break;
}
numDeleted += (found - next);
next = found + 1;
}
if (isSubSeq)
{
if (anySubSeqFound)
{
if (numDeleted < minToDelete)
minToDelete = numDeleted;
}
else
{
anySubSeqFound = true;
minToDelete = numDeleted;
}
}
++first;
}
return anySubSeqFound;
}
int main()
{
int minToDelete;
if (check("thistext", "text", minToDelete))
cout << "yes, delete " << minToDelete << endl;
else
cout << "no" << endl;
if (check("cutefriendship", "crisp", minToDelete))
cout << "yes, delete " << minToDelete << endl;
else
cout << "no" << endl;
}
Live Demo

Related

issue with pointers and count

I need to build a code where it takes a 2d array of char and checks if its palindrome the second function uses the first one to see how many arrays are palindrome my issue with the code is that every time I get count is 0; I know the issue is in the second function but don't know where
#include <iostream>
using namespace std;
int CountPal(char M[][5], int rows);
int pal(char* S) {
char *p, *start, flag = 1;
p = S;
while(*p != NULL) {
++p;
}
--p;
for(start = S; p >= start && flag;) {
if(*p == *start) {
--p;
start++;
} else
flag = 0;
}
}
int main() {
int x;
cout << "please enter the number of rows " << endl;
cin >> x;
char M[5][5];
cout << "before test" << endl;
cout << CountPal(M, x) << endl;
cout << "After test" << endl;
system("pause");
}
int CountPal(char M[][5], int rows) {
int count = 0;
cout << "please enter the string " << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < 5; j++) {
cin >> M[i][j];
}
for(int i = 0; i < rows; i++) {
char* S;
S = &M[i][0];
if(pal(S) == 1) count++;
}
}
return count;
}
I think your problem is in int pal(char* S) function. You want it to return 1 if a given string of your 2d array is a palindrome to up your count by 1. And anything other than 1 would be non palindrome string.
So i think you should add a return statement after the end of your int pal(char* S) function like this;
int pal(char* S) {
char *p, *start, flag = 1;
p = S;
while(*p != NULL) {
++p;
}
--p;
for(start = S; p >= start && flag;) {
if(*p == *start) {
--p;
start++;
} else
flag = 0;
}
return flag;
}
You could even change your function to bool data type. It's more proper because you only want to return "true" or "false" values.

isPalindrome homework exercise

Write a program that uses the function isPalindrome given in Example 6-6 (Palindrome). Test your program on the following strings:
madam, abba, 22, 67876, 444244, trymeuemyrt
Modify the function isPalindrome of Example 6-6 so that when determining whether a string is a palindrome, cases are ignored, that is, uppercase and lowercase letters are considered the same.
The isPalindrome function from Example 6-6 has been included below for your convenience.
bool isPalindrome(string str)
{
int length = str.length();
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length – 1 – i]) {
return false;
} // if
} // for loop
return true;
}// isPalindrome
Your program should print a message indicating if a string is a palindrome:
madam is a palindrome
My program so far is this
#include <iostream>
#include <string.h>
using namespace std;
int main () {
bool isPalindrome (string str);
string str;
int length = str.length();
cout << "Enter a string: ";
getline (cin,str);
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length -1 -i]) {
cout << str << "Is not a Palindrome";
return false;
} else if (str[i] == str[length -1 -i] && toupper(str[i]) != islower(str[i])) {
cout << str << "Is a Palindrome";
} // for loop
return true;
}
}
I do not know what im doing wrong I sent everything to make sure it matches the word backwards and then when it is true it will return true. I am very to new to programming and I am sorry if my code is a little sloppy.
This is a modification of your code. It wasn't too logical that you were declaring the function inside so i just put it outside.
#include <iostream>
#include <string.h>
using namespace std;
bool isPalindrome(string str) {
int length = str.length();
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length -1 -i]) {
cout << str << "Is not a Palindrome";
return false;
} else if (str[i] == str[length -1 -i] && toupper(str[i]) != islower(str[i])) {
cout << str << "Is a Palindrome";
} // for loop
return true;
}
return false;
}
int main () {
string str;
cout << "Enter a string: ";
getline (cin,str);
isPalindrome(str);
}
public static bool IsPalindrome(string value)
{
int i = 0;
int j = value.Length - 1;
while (true)
{
if (i > j)
{
return true;
}
char a = value[i];
char b = value[j];
if (char.ToLower(a) != char.ToLower(b))
{
return false;
}
i++;
j--;
}
}
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 1000
bool isPalindrome(int x){
int c[MAX];
int i = 0;
int j;
int k = 0;
bool z;
if(x < 0){
return false;
}
while (x != 0){
int r = x % 10;
c[i] = r;
i++;
x = x / 10;
}
for (j = i - 1; j > -1; j--) {
printf("%d ", c[j]);
}
for(k = 0; k <= (i / 2); k++){
if(c[k] == c[i - k - 1]){
z = true;
}
else
{
z = false;
}
}
return z;
}

Compress string of bits in place (C++) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to make a function that compresses a string of 0's and 1's. That is, "00010111100101" goes to "30104100101". Should this be a very complicated procedure? My code is looking messy.
The prototype should look like:
static void compress_bitstring(std::string& str) {
// compression algorithm
}
Ok, here's my final answer, with compression of runlengths > 9 and refactoring duplicating code.
template<typename T>
std::string to_string(T t)
{
std::ostringstream str;
str << t;
return str.str();
}
static void compress_bitstring(std::string& str)
{
std::string result;
int count = 0;
char last = 0;
auto add_to_result = [&]{
if (count > 2)
result += to_string(count) + last;
else for (auto loop=0; loop<count; ++loop)
result += last;
};
for (char ch : str)
{
if ((last == 0 || ch == last) && count < 9)
++count;
else {
add_to_result();
count = 1;
}
last = ch;
}
add_to_result();
swap(result, str);
}
int main()
{
std::string str("00010111100101");
compress_bitstring(str);
assert(str == "30104100101");
str = "0001011110010100000000000000000000000001";
compress_bitstring(str);
assert(str == "301041001019090701");
return 0;
}
Here's my approach
update realized my answer could be a lot shorter, and more comprehensive (thanks to Nik Bougalis)
#include <iostream>
#include <sstream>
#include <string>
static void compress_bitstring(std::string& str) {
std::stringstream ss;
std::string cur_num;
int count = 1;
for (int i = 0; i < str.size()-1; ++i){
if (str[i] == str[i+1]){
++count;
cur_num = str[i];
if (i == str.size()-2){
ss << count << cur_num;
} else{
if (count == 9){
ss << count << cur_num;
count = 0;
}
}
} else if (count > 2){
ss << count << cur_num;
count = 1;
if (i == str.size()-2){
ss << str[i+1];
}
} else if (i != str.size()-2){
for (int j = 0; j < count; ++j){
ss << str[i];
}
count = 1;
} else{
ss << str[i] << str[i];
}
}
str = ss.str();
}
static void decode_bitstring(std::string& str){
int i = 0;
int count;
std::stringstream ss;
while (i < str.size()){
std::stringstream to_int;
to_int << str[i];
to_int >> count;
if (count > 1){
for (int j = 0; j < count; ++j){
ss << str[i+1];
}
i = i + 2;
} else{
ss << str[i];
++i;
}
}
str = ss.str();
}
int main(){
std::string binary_num = "0001011110010100000000000000000000000001";
std::cout << binary_num << '\n';
compress_bitstring(binary_num);
std::cout << binary_num << '\n';
decode_bitstring(binary_num);
std::cout << binary_num << '\n';
return 0;
}
edit 2 I also gave a decoder option.
output:
nero#ubuntu:~/learn$ ./lc
0001011110010100000000000000000000000001
301041001019090701
0001011110010100000000000000000000000001
template<typename T>
std::string to_string(T t)
{
std::ostringstream str;
str << t;
return str.str();
}
static void compress_bitstring(std::string& str)
{
std::string result;
int count = 0;
char last = 0;
for (char ch : str)
{
if (last == 0 || ch == last)
++count;
else {
if (count > 2)
result += to_string(count) + last;
else for (auto loop=0; loop<count; ++loop)
result += last;
count = 1;
}
last = ch;
}
if (count > 2)
result += to_string(count) + last;
else for (auto loop=0; loop<count; ++loop)
result += last;
swap(result, str);
}
int main()
{
std::string str("00010111100101");
compress_bitstring(str);
assert(str == "30104100101");
return 0;
}
std::string compress1(std::string &s) {
char c = s[0];
int counter = 1;
std::stringstream ss;
for (size_t i = 1; i < s.length(); i++) {
if (c != s[i]) {
if (counter > 2) ss << counter;
if (counter == 2) ss << c;
ss << c;
counter = 0;
}
c = s[i];
counter++;
}
if (counter > 2) ss << counter;
if (counter == 2) ss << c;
ss << c;
return ss.str();
}
Output:
compress1("00010111100101"): 30104100101
compress1("000101111001011"): 301041001011
Here I post my logic which may help you.
#include<string.h>
int main(){
char* str ="00010111100101";
char* result = malloc(strlen(str)+1);
int i = 0;
char *q;
char * p = str;
result[i++] = str[0];
do{
q = strchr(str,str[0]=='0'?'1':'0'); //Searching for the opposite char.
result[i++] = (q == '\0'? str+strlen(str) : q ) - p + '0'; // Storing the difference in result
str = p = q; //updating str and p
}while(q != '\0');
result[i] = '\0';
printf("Compressed Result = %s",result);
return 0;
}
http://codepad.org/Qn8NEuB7

Check if a string is palindrome

I need to create a program that allows a user to input a string and my program will check to see if that string they entered is a palindrome (word that can be read the same backwards as it can forwards).
Note that reversing the whole string (either with the rbegin()/rend() range constructor or with std::reverse) and comparing it with the input would perform unnecessary work.
It's sufficient to compare the first half of the string with the latter half, in reverse:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string s;
std::cin >> s;
if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
std::cout << "is a palindrome.\n";
else
std::cout << "is NOT a palindrome.\n";
}
demo: http://ideone.com/mq8qK
Just compare the string with itself reversed:
string input;
cout << "Please enter a string: ";
cin >> input;
if (input == string(input.rbegin(), input.rend())) {
cout << input << " is a palindrome";
}
This constructor of string takes a beginning and ending iterator and creates the string from the characters between those two iterators. Since rbegin() is the end of the string and incrementing it goes backwards through the string, the string we create will have the characters of input added to it in reverse, reversing the string.
Then you just compare it to input and if they are equal, it is a palindrome.
This does not take into account capitalisation or spaces, so you'll have to improve on it yourself.
bool IsPalindrome(const char* psz)
{
int i = 0;
int j;
if ((psz == NULL) || (psz[0] == '\0'))
{
return false;
}
j = strlen(psz) - 1;
while (i < j)
{
if (psz[i] != psz[j])
{
return false;
}
i++;
j--;
}
return true;
}
// STL string version:
bool IsPalindrome(const string& str)
{
if (str.empty())
return false;
int i = 0; // first characters
int j = str.length() - 1; // last character
while (i < j)
{
if (str[i] != str[j])
{
return false;
}
i++;
j--;
}
return true;
}
// The below C++ function checks for a palindrome and
// returns true if it is a palindrome and returns false otherwise
bool checkPalindrome ( string s )
{
// This calculates the length of the string
int n = s.length();
// the for loop iterates until the first half of the string
// and checks first element with the last element,
// second element with second last element and so on.
// if those two characters are not same, hence we return false because
// this string is not a palindrome
for ( int i = 0; i <= n/2; i++ )
{
if ( s[i] != s[n-1-i] )
return false;
}
// if the above for loop executes completely ,
// this implies that the string is palindrome,
// hence we return true and exit
return true;
}
#include <iostream>
#include <string>
bool isPalindrome(const std::string& str){
if(str.empty()) return true;
std::string::const_iterator itFirst = str.begin();
std::string::const_iterator itLast = str.end() - 1;
while(itFirst < itLast) {
if (*itFirst != *itLast)
return false;
++itFirst;
--itLast;
}
return true;
}
int main(){
while(1){
std::string input;
std::cout << "Eneter a string ...\n";
std::cin >> input;
if(isPalindrome(input)){
std::cout << input << " is palindrome.\n";
} else {
std::cout << input << " is not palindrome.\n";
}
}
return 0;
}
Check the string starting at each end and meet in the middle. Return false if there is a discrepancy.
#include <iostream>
bool palidromeCheck(std::string str) {
for (int i = 0, j = str.length()-1; i <= j; i++, j--)
if (str[i] != str[j])
return false;
return true;
}
int main(){
std::cout << palidromeCheck("mike");
std::cout << palidromeCheck("racecar");
}
Reverse the string and check if original string and reverse are same or not
I'm no c++ guy, but you should be able to get the gist from this.
public static string Reverse(string s) {
if (s == null || s.Length < 2) {
return s;
}
int length = s.Length;
int loop = (length >> 1) + 1;
int j;
char[] chars = new char[length];
for (int i = 0; i < loop; i++) {
j = length - i - 1;
chars[i] = s[j];
chars[j] = s[i];
}
return new string(chars);
}

how to check whether 2 strings are rotations to each other ?

Given 2 strings, design a function that can check whether they are rotations to each other without making any changes on them ? The return value is boolean.
e.g ABCD, ABDC, they are not rotations. return false
ABCD, CDAB or DABC are rotations. return true.
My solution:
shift one of them to right or left one position and then compare them at each iteration.
If they are not equal at all iterations, return false. Otherwise, return true.
It is O(n). Are there other more efficient solutions ?
What if the contents of them cannot be changed ?
thanks
Concatenate the given string with the given string.
Search for the target string in the concatenated string.
Example:
Given = CDAB
After step 1, Concatenated = CDABCDAB
After step 2, Success CDABCDAB
^^^^
Rather than shifting one of them, it might be more efficient to use two index variables. Start one at 0 each time and the other at each of the possible positions (0 to N-1) and increment it mod N.
If you can't modify the strings, just take the first character of string1 and compare it to each character of string2. When you get a match, compare the second char of string1 to the next char of string2, and so on.
Pseudocode:
len = strlen(string1);
len2 = strlen(string2);
if( len != len2 )
printf("Nope.");
for( int i2=0; i2 < len; i2++ ) {
for( int i1=0; i1<len; i1++ ) {
if( string1[i1] != string2[(i2+i1)%len] )
break;
}
if( i1 == len ) {
print("Yup.");
break;
}
}
A simple one would be:
(s1+s1).find(s2) != string::npos && s1.size() == s2.size();
#include <iostream>
#include <cstring>
#include<string>
using namespace std;
void CompareString(string, string, int);
int ComputeStringLength(string str);
int main()
{
string str = ""; string str1 = ""; int len = 0, len1 = 0;
cout << "\nenter string ";
cin >> str;
cout << "\nenter string 2 to compare:- ";
cin >> str1;
len = ComputeStringLength(str);
len1 = ComputeStringLength(str1);
if (len == len1)
CompareString(str, str1, len);
else
cout << "rotation not possible";
getchar();
return 0;
}
int ComputeStringLength(string str)
{
int len = 0;
for (int i = 0; str[i] != '\0'; i++)
{
len++;
}
return len;
}
void CompareString(string str, string str1, int n)
{
int index = 0, flag = 0, curr_index = 0, count1 = 0, flagj = 0;
for (int i = 0; i<n; i++)
{
for (int j = flagj; j<n; j++)
{
if (str[i] == str1[j])
{
index = j;
flagj =j;
count1++;
flag++;
if (flag == 1)
{
curr_index = index;
}
break;
}
}
}
int temp = count1;
if (count1 != n)
{
if (curr_index>=0)
{
int k = 0;
for (int i = n - 1; i>n - curr_index - 1; i--)
{
if (str[i] == str1[k])
{
temp++;
k++;
}
}
}
if (temp == n)
{
cout << "\n\nstring is same after rotation";
}
else
{
cout << "\n\nstring is not same after rotation";
}
}
else
{
cout << "\n\nstring is same after rotation";
}
}
https://dsconceptuals.blogspot.in/2016/10/a-program-to-check-if-strings-are.html