Given a string, find lexicographically next string.
Examples:
Input : geeks
Output : geekt
The last character 's' is changed to 't'.
Input : raavz
Output : raawz
Since we can't increase last character,
we increment previous character.
Input : zzz
Output : zzza
If string is empty, we return ‘a’. If string contains all characters as ‘z’, we append ‘a’ at the end. Otherwise we find first character from end which is not z and increment it.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
string nextWord(string s)
{
if (s == "" )
return "a" ;
int i = s.length() - 1;
while (s[i] == 'z' && i >= 0)
i--;
if (i == -1)
s = s + 'a' ;
else
s[i]++;
return s;
}
int main()
{
string str = "samez" ;
cout << nextWord(str);
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static String nextWord(String str)
{
if (str == "" )
return "a" ;
int i = str.length() - 1 ;
while (str.charAt(i) == 'z' && i >= 0 )
i--;
if (i == - 1 )
str = str + 'a' ;
else
str = str.substring( 0 , i) +
( char )(( int )(str.charAt(i)) + 1 ) +
str.substring(i + 1 );
return str;
}
public static void main (String[] args)
{
String str = "samez" ;
System.out.print(nextWord(str));
}
}
|
Python3
def nextWord(s):
if (s = = " " ):
return "a"
i = len (s) - 1
while (s[i] = = 'z' and i > = 0 ):
i - = 1
if (i = = - 1 ):
s = s + 'a'
else :
s = s.replace(s[i], chr ( ord (s[i]) + 1 ), 1 )
return s
if __name__ = = '__main__' :
str = "samez"
print (nextWord( str ))
|
C#
using System;
class GFG
{
public static string nextWord( string str)
{
if (str == "" )
{
return "a" ;
}
int i = str.Length - 1;
while (str[i] == 'z' && i >= 0)
{
i--;
}
if (i == -1)
{
str = str + 'a' ;
}
else
{
str = str.Substring(0, i) +
( char )(( int )(str[i]) + 1) +
str.Substring(i + 1);
}
return str;
}
public static void Main( string [] args)
{
string str = "samez" ;
Console.Write(nextWord(str));
}
}
|
Javascript
<script>
function nextWord(s)
{
if (s == "" )
return "a" ;
var i = s.length - 1;
while (s[i] == 'z' && i >= 0)
i--;
if (i == -1)
s = s + 'a' ;
else
s[i] = String.fromCharCode(s[i].charCodeAt(0)+1);
return s.join( '' );
}
var str = "samez" .split( '' );
document.write( nextWord(str));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!