Skip to content

Commit cec268c

Browse files
committed
Day 41 next permutation of string
1 parent f6572cb commit cec268c

File tree

2 files changed

+58
-3
lines changed

2 files changed

+58
-3
lines changed

README.md

+4-3
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44

55
| Current Status| Stats |
66
| :------------: | :----------: |
7-
| Total Problems | 59 |
8-
| Current Streak | 40 |
9-
| Longest Streak | 40 ( August 17, 2015 - September 25, 2015 ) |
7+
| Total Problems | 60 |
8+
| Current Streak | 41 |
9+
| Longest Streak | 41 ( August 17, 2015 - September 26, 2015 ) |
1010

1111
</center>
1212

@@ -92,6 +92,7 @@ Include contains single header implementation of data structures and some algori
9292
| Problem | Solution |
9393
| :------------ | :----------: |
9494
| Implementation of Robin-Karp algorithm for string search | [robinKarpStringMatching.cpp](string_problmes/robinKarpStringMatching.cpp) |
95+
| Find next permutation of a given string, ie. rearrange the given string sucht a way that is next lexicographically greater string than given string | [next_permutation.cpp](string_problems/next_permutations.cpp)|
9596

9697
### Math Problems
9798
| Problem | Solution |

string_problems/next_permutation.cpp

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Implement next permutation algorithm. i.e
3+
* Given a word w, rearrange the letters of w to construct another word s in such a way that
4+
* s is lexicographically greater than w.
5+
* In case of multiple possible answers, find the lexicographically smallest one.
6+
* Example:
7+
* ab --> ba
8+
* bb --> bb
9+
* hefg --> hegf
10+
* dhck --> dhkc
11+
* dkhc --> hcdk
12+
*/
13+
14+
#include <iostream>
15+
16+
std::string
17+
next_permutation( std::string str)
18+
{
19+
int len = str.length();
20+
int i = len -1;
21+
// We will iterate string from end, and once we have encountered a pair of letters
22+
// such that str[i] < str[i-1] , i-1 would become our pivot
23+
while( i > 0 && str[i] <= str[i-1] ) {
24+
--i;
25+
}
26+
if ( i == 0 ) {
27+
return str;
28+
}
29+
//our pivot right now would be str[i-1]
30+
int j = len - 1;
31+
while( j >= i && str[j] <= str[i-1] ) {
32+
--j;
33+
}
34+
std::swap(str[i-1], str[j]);
35+
j = len - 1;
36+
//reverse the suffix
37+
while( i < j ) {
38+
std::swap(str[i], str[j]);
39+
--j;
40+
++i;
41+
}
42+
return str;
43+
}
44+
45+
int main()
46+
{
47+
std::string str, str_next;
48+
std::cout << "Enter a string : ";
49+
std::cin >> str;
50+
str_next = next_permutation(str);
51+
std::cout << "Next permutation of " << str << " is "
52+
<< str_next << std::endl;
53+
return 0;
54+
}

0 commit comments

Comments
 (0)