this is how we can do it:
string s("abcdef"); reverse(s.begin(), s.end());
string s("abcdef"); reverse(s.begin(), s.end());
//Use a lookup table, this can be
size_t lookup[26];
// or just a unsigned int, in which the first 26 bits
// is used to mark the presence of a character.
size_t lookup;
Scan the first string and mark the characters in the lookup
Scan the second string, if the character is found in lookup,
then copy it to output string.
Use a stack.
while( not end of input )
{
ch = input character
if ( ch is '(' ) then push it to stack.
else pop from stack., and if the poped item is not '(' then error.
}
The stack should be empty now.
1. Append the second the string with itself, we get, deabcdeabc O(n)
2. When we do step 2, notice that the first string occurs as a substring.
3. Search for the original string in the appended string. (O(2n) for space + O(n) time if suffix trees are used and this step depends on which sub string search algo we use)
|---||---|
deabcdeabc
^^^^^
Method 1:
I am a good boy
<------------->
yob doog a ma I
<-> <--> <-> <-> <->
boy good a am I
Method2
Another way to do it is, allocate as much memory as the input for the final output. Start from the right of the string and copy the words one by one to the output.
Input : I am a good boy
<--
<-------
<---------
<------------
<--------------
Output : boy
: boy good
: boy good a
: boy good a am
: boy good a am I
The only problem to this solution is the extra space required for the output and one has to write this code really well as we are traversing the string in the reverse direction and there is no null at the start of the string to know we have reached the start of the string!. One can use the strtok() function to breakup the string into multiple words and rearrange them in the reverse order later.
Method3
Create a linked list like
+---+ +----------+ +----+ +----------+ +---+ +----------+
| I | -> || -> | am | -> | | -> | a | -> | | --+
+---+ +----------+ +----+ +----------+ +---+ +----------+ |
|
|
+-------------------------------------------------------------------------+
|
| +------+ +----------+ +-----+ +------+
+---> | good | -> || -> | boy | -> | NULL |
+------+ +----------+ +-----+ +------+
Now its a simple question of reversing the linked list!.
lookup['z'-'a'] = {0}
Pass 1: Traverse the string, and perform ++lookup[string[i]];
Pass 2: Traverse the string, and the first char for which lookup[string[i]] == 1 is the required char.
bool lookup[26] = {false}
scan the first string and initialize the lookup
scan the second string and check if all the alpahbets are present.
cur next
| |
accccefgggggg
GetRepSeq(const char* str, char **start, size_t *len)
{
const char* next = str + 1;
const char* cur = str;
size_t cur_len = 1;
*start = 0;
*len = 1;
while (*next)
{
if ( *next == *cur )
{
++next;
++cur_len;
}
else
{
/* we just encountered a non equal char */
if ( cur_len >= *len )
{
*len = cur_len;
*start = cur;
}
cur = next;
++next;
}
}
}