


C++ program: find the longest subsequence of numbers with the same left and right rotation
In this problem, we need to find the maximum length of the subsequence with the same left and right rotation. Left rotation means moving all the characters in the string to the left, and moving the first character at the end. Right rotation means moving all string characters to the right and moving the last character to the beginning.
Problem Statement – We are given a string str containing numbers and need to find a subsequence of maximum length with the same left and right rotation.
Example
Input-str="323232",
Output– 6
Explanation - The longest subsequence with the same left and right rotation is "323232". Rotate it left to ‘232323’ and rotate it right to ‘232323’.
Input-str = ‘00010100’
Output– 6
Explanation – The longest subsequence with the same left and right rotation is "000000".
Input-str = ‘092312110431010’
Output– 6
Explanation – There are 2 possible subsequences of length 6 with the same left and right rotation. The first one is "010101" and the second one is "101010".
method 1
In this method we will find all possible subsequences of the given string. After that we will check if the left and right rotation of the string is the same. We will use a recursive method to find all possible subsequences.
algorithm
Initialize the "maxLen" global variable to zero to store the length of the longest subsequence that is the same for left and right rotations.
Define the isRightSameLeft() function to check whether the left and right rotations of the string are the same.
Inside the function, use the substr() method to rotate the string left and right.
getAllSubSeq() function is used to find all possible subsequences of a given string.
Define base case. If str is empty, we get the subsequence and execute the isRightSameLeft() function to check if the subsequence has the same left and right rotation. If so, update the value of the "maxLen" variable if its length is greater than the current value of "maxLen".
Make a recursive call after removing the first character from "str" and appending the "out" string.
After removing the first character and leaving the "out" string unchanged, make another recursive function call. In this recursive call, we exclude the first character of "str".
Example
#include <iostream> #include <string> using namespace std; // Defining global variable to store the length of the longest subsequence according to the given condition int maxLen = 0; // function to check if the string is the same after the left rotation bool isRightSameLeft(string str) { int len = str.length(); return str.substr(1, len - 1) + str[0] == str[len - 1] + str.substr(0, len - 1); } // function to get all subsequences of a string void getAllSubSeqs(string str, string out) { // If the string is empty, we get the subsequences. Check if its left and right rotation is the same if (str.empty()) { if (isRightSameLeft(out)) maxLen = max(maxLen, (int)out.length()); return; } // Recursive case remove the first character from str, and add it to the output getAllSubSeqs(str.substr(1), out + str[0]); // remove the first character from str, and drop it if (str.length() > 1) getAllSubSeqs(str.substr(1), out); } int main() { string str = "323232"; string out = ""; getAllSubSeqs(str, out); cout << "The longest subsequence of str having same left and right rotation is " << maxLen; return 0; }
Output
The longest subsequence of str having same left and right rotation is 6
Time complexity - O(N*2N). Here O(N) for comparing left and right rotations and O(2N) for finding all possible subsequences.
Space Complexity - O(1) since we don't use extra space.
Method 2
Here, we have optimized the above method. We can observe the solution of the sample input. Left and right rotations of a subsequence are the same only if the subsequence contains the same character or alternately contains two different characters and is of even length.
algorithm
Use two nested loops to combine any two numbers.
Define the 'cnt' variable to find the length of a subsequence containing two numbers alternately, and initialize it to zero.
Define the "first" variable of Boolean type to track whether the next character should be the i-th or j-th character.
Use a loop to traverse the string.
If first == true and str[k] - '0' == I, alternate the value of 'first' and increment 'cnt' by 1.
If first == false and str[k] - '0' == j, alternate the value of 'first' again and increment 'cnt' by 1.
If i and j are not equal and the "cnt" value is odd, decrement it by 1.
If the cnt value is greater than "res", update the value of the "res" variable.
Example
#include <bits/stdc++.h> using namespace std; int getLongSubSeq(string str) { // Store the length of the string int len = str.size(), res = 0; // Traverse the all possible combination of two digits for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { // to store the length of an alternating sequence of the current combination int cnt = 0; // to track the turn of the ith or jth digit bool first = true; // traverse the string for (int k = 0; k < len; k++) { // If the current digit is equal to I, and the first is true, increment the count if (first == true and str[k] - '0' == i) { first = false; cnt++; } else if (first == false and str[k] - '0' == j) { // If the current digit is equal to j, and the first is false, increment the count first = true; cnt++; } } // If the sequence is odd and i and j are different, decrement the count if (i != j and cnt % 2 == 1) cnt--; // Update the answer res = max(cnt, res); } } return res; } int main() { string str = "00010100"; cout << "The longest subsequence of str having same left and right rotation is " << getLongSubSeq(str); return 0; }
Output
The longest subsequence of str having same left and right rotation is 6
Time complexity - O(10*10*N), because we find subsequences from strings containing combinations of numbers.
Space complexity - O(1), because we don't use dynamic space.
This tutorial teaches us two methods to find the longest subsequence containing the same left and right rotation. The first method is the simple method, this method is very time consuming and we cannot use it for large amount of inputs.
The second method is optimized and its time complexity is almost equal to O(N).
The above is the detailed content of C++ program: find the longest subsequence of numbers with the same left and right rotation. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



As a lifestyle sharing platform, Xiaohongshu is where more and more users choose to publish their own video content and share their daily life with other users. Many users may encounter a problem when posting videos: How to check the time when they or others posted videos? 1. How to check the time when Xiaohongshu released a video? 1. Check the time when you posted the video. To check the time when you posted the video, you must first open the Xiaohongshu app and log in to your personal account. At the bottom of the personal homepage interface, there will be an option marked "Creation". After clicking to enter, you will see a column called "Video". Here you can browse a list of all published videos and easily check when they were published. There is a "View Details" button in the upper right corner of each video. After clicking

Standby is a lock screen mode that activates when the iPhone is plugged into the charger and oriented in horizontal (or landscape) orientation. It consists of three different screens, one of which is displayed full screen time. Read on to learn how to change the style of your clock. StandBy's third screen displays times and dates in various themes that you can swipe vertically. Some themes also display additional information, such as temperature or next alarm. If you hold down any clock, you can switch between different themes, including Digital, Analog, World, Solar, and Floating. Float displays the time in large bubble numbers in customizable colors, Solar has a more standard font with a sun flare design in different colors, and World displays the world by highlighting

The inability of the laptop to type numbers 1-9 is caused by a setting problem. The solution is: 1. Press "win+r" to open the run and enter cmd and press Enter; 2. In the command prompt interface, enter osk and press Enter; 3. Click "Options" on the virtual keyboard and check "Turn on numeric keypad"; 4. Enable "numlock key".

The ability to generate random numbers or alphanumeric strings comes in handy in many situations. You can use it to spawn enemies or food at different locations in the game. You can also use it to suggest random passwords to users or create filenames to save files. I wrote a tutorial on how to generate random alphanumeric strings in PHP. I said at the beginning of this post that few events are truly random, and the same applies to random number or string generation. In this tutorial, I'll show you how to generate a pseudo-random alphanumeric string in JavaScript. Generating Random Numbers in JavaScript Let’s start by generating random numbers. The first method that comes to mind is Math.random(), which returns a float

Representing numbers as output is an interesting and important task when writing a program in any language. For integer types (data of type short, long, or medium), it is easy to represent numbers as output. For floating point numbers (float or double type), sometimes we need to round them to a specific number of decimal places. For example, if we want to represent 52.24568 as three decimal places, some preprocessing is required. In this article, we will introduce several techniques to represent floating point numbers to a specific number of decimal places by rounding. Among the different approaches, it is important to use a C-like format string, use the precision argument, and use the round() function from the math library. Let’s look at them one by one. with

We all know numbers that are not the square of any number, such as 2, 3, 5, 7, 8, etc. There are N non-square numbers, and it is impossible to know every number. So, in this article, we will explain everything about squareless or non-square numbers and ways to find the Nth non-square number in C++. Nth non-square number If a number is the square of an integer, then the number is called a perfect square. Some examples of perfect square numbers are -1issquareof14issquareof29issquareof316issquareof425issquareof5 If a number is not the square of any integer, then the number is called non-square. For example, the first 15 non-square numbers are -2,3,5,6,

In the PHP programming language, the is_numeric() function is a very commonly used function, used to determine whether a variable or value is a number. In actual programming, it is often necessary to verify the value entered by the user to determine whether it is a numeric type. In this case, the is_numeric() function can be used to determine. 1. Introduction to is_numeric() function The is_numeric() function is a function used to detect whether a variable or value is a number. Returns tru if the variable or value is a number

In this article, we will discuss the problem of finding numbers between 1 and n (given) that are not divisible by any number between 2 and 10. Let us understand this with some examples - Input:num=14Output:3Explanation:Therearethreenumbers,1,11,and13,whicharenotdivisible.Input:num=21Output:5Explanation:Therearefivenumbers1,11,13,17,and19,whicharenotdivisible. Solved Simple method if
