We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
publicstaticstringbiggerIsGreater(stringw){varnext=NextPermutation(w);returnnext;}staticstringNextPermutation(stringsource){//https://www.nayuki.io/page/next-lexicographical-permutation-algorithmvarsrc=source.ToCharArray();// Find longest non-increasing suffix - longest weakly decreasing sequencevari=src.Length-1;while(i>0&&src[i-1]>=src[i])i-=1;// i is index of suffix// If 0 then we're at last permutationif(i<=0)return"no answer";// Pivot is the index just before the longest non-increasing suffix// Find rightmost element greater than the pivotintj=src.Length-1;while(src[j]<=src[i-1])j--;// Now the value src[j] will become the new pivot// Assertion: j >= i// Swap the pivot with j(src[i-1],src[j])=(src[j],src[i-1]);// Reverse the suffixj=src.Length-1;while(i<j){(src[i],src[j])=(src[j],src[i]);i++;j--;}returnnewstring(src);}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Bigger is Greater
You are viewing a single comment's thread. Return to all comments →
C#