用于查找给定字符串的下一个更大排列的算法

时间:2009-10-25 23:54:23

标签: algorithm

我想要一种有效的算法来找到给定字符串的下一个更大的排列。

13 个答案:

答案 0 :(得分:136)

Wikipedia在字典顺序生成方面有一个很好的article。它还描述了一种生成下一个排列的算法。

引用:

以下算法在给定排列后按字典顺序生成下一个排列。它就地改变了给定的排列。

  
      
  1. 找到i的最高索引s[i] < s[i+1]。如果不存在这样的索引,则排列是最后的排列。
  2.   
  3. 找到j > i的最高索引s[j] > s[i]。这样的j必须存在,因为i+1就是这样的索引。
  4.   
  5. s[i]交换s[j]
  6.   
  7. 将索引i之后的所有元素的顺序颠倒到最后一个元素。
  8.   

答案 1 :(得分:14)

这里描述了一个很好的解决方案:https://www.nayuki.io/page/next-lexicographical-permutation-algorithm。并且,如果存在下一个排列,则返回它的解决方案,否则返回false

function nextPermutation(array) {
    var i = array.length - 1;
    while (i > 0 && array[i - 1] >= array[i]) {
        i--;
    }

    if (i <= 0) {
        return false;
    }

    var j = array.length - 1;

    while (array[j] <= array[i - 1]) {
        j--;
    }

    var temp = array[i - 1];
    array[i - 1] = array[j];
    array[j] = temp;

    j = array.length - 1;

    while (i < j) {
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
        i++;
        j--;
    }

    return array;
}

答案 2 :(得分:4)

作业?无论如何,可以看一下C ++函数std :: next_permutation,或者这个:

http://blog.bjrn.se/2008/04/lexicographic-permutations-using.html

答案 3 :(得分:1)

我们可以使用以下步骤找到给定字符串S的下一个最大的词典字符串。

1. Iterate over every character, we will get the last value i (starting from the first character) that satisfies the given condition S[i] < S[i + 1]
2. Now, we will get the last value j such that S[i] < S[j]
3. We now interchange S[i] and S[j]. And for every character from i+1 till the end, we sort the characters. i.e., sort(S[i+1]..S[len(S) - 1])

给定字符串是S的下一个最大词典字符串。也可以在C ++中使用next_permutation函数调用。

答案 4 :(得分:1)

nextperm(a,n)

1. find an index j such that a[j….n - 1] forms a monotonically decreasing sequence.
2. If j == 0 next perm not possible
3. Else 
    1. Reverse the array a[j…n - 1]
    2. Binary search for index of a[j - 1] in a[j….n - 1]
    3. Let i be the returned index
    4. Increment i until a[j - 1] < a[i]
    5. Swap a[j - 1] and a[i]


O(n) for each permutation.

答案 5 :(得分:1)

Users
 - userID
    - User Info
    - User Roles (if using role based authorization)

Other Data Collections
 - Other Data Documents
    - Other Sub Collections 

}

答案 6 :(得分:1)

  

使用@Fleischpfanzerl引用的来源

Next Lexicographical Permutation

我们按照以下步骤查找下一个词典编排:

enter image description here

nums = [0,1,2,5,3,3,0]
nums = [0]*5
curr = nums[-1]
pivot = -1
for items in nums[-2::-1]:
    if items >= curr:
        pivot -= 1
        curr = items
    else:
        break
if pivot == - len(nums):
    print('break')     # The input is already the last possible permutation

j = len(nums) - 1
while nums[j] <= nums[pivot - 1]:
    j -= 1
nums[j], nums[pivot - 1] = nums[pivot - 1], nums[j]
nums[pivot:] = nums[pivot:][::-1]

> [1, 3, 0, 2, 3, 5]

因此,想法是: 这个想法是遵循步骤-

  1. 从数组的末尾查找索引“ pivot”,使nums [i-1]
  2. 找到索引j,例如nums [j]> nums [pivot-1]
  3. 交换这两个索引
  4. 从枢轴开始倒转后缀

答案 7 :(得分:1)

仅需使用两种简单的算法即可解决该问题,只需在O(1)的额外空间和O(nlogn)的时间中找到较小的元素,并且易于实现。

要清楚地了解这种方法。观看此视频:https://www.youtube.com/watch?v=DREZ9pb8EQI

答案 8 :(得分:0)

这里描述了一个有效的解决方案:https://www.nayuki.io/page/next-lexicographical-permutation-algorithm。 如果您正在寻找

源代码:

/**
     * method to find the next lexicographical greater string
     * 
     * @param w
     * @return a new string
     */
    static String biggerIsGreater(String w) {
        char charArray[] = w.toCharArray();
        int n = charArray.length;
        int endIndex = 0;

        // step-1) Start from the right most character and find the first character
        // that is smaller than previous character.
        for (endIndex = n - 1; endIndex > 0; endIndex--) {
            if (charArray[endIndex] > charArray[endIndex - 1]) {
                break;
            }
        }

        // If no such char found, then all characters are in descending order
        // means there cannot be a greater string with same set of characters
        if (endIndex == 0) {
            return "no answer";
        } else {
            int firstSmallChar = charArray[endIndex - 1], nextSmallChar = endIndex;

            // step-2) Find the smallest character on right side of (endIndex - 1)'th
            // character that is greater than charArray[endIndex - 1]
            for (int startIndex = endIndex + 1; startIndex < n; startIndex++) {
                if (charArray[startIndex] > firstSmallChar && charArray[startIndex] < charArray[nextSmallChar]) {
                    nextSmallChar = startIndex;
                }
            }

            // step-3) Swap the above found next smallest character with charArray[endIndex - 1]
            swap(charArray, endIndex - 1, nextSmallChar);

            // step-4) Sort the charArray after (endIndex - 1)in ascending order
            Arrays.sort(charArray, endIndex , n);

        }
        return new String(charArray);
    }

    /**
     * method to swap ith character with jth character inside charArray
     * 
     * @param charArray
     * @param i
     * @param j
     */
    static void swap(char charArray[], int i, int j) {
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
    }

如果您要查找相同的视频说明,则可以访问here

答案 9 :(得分:0)

我遇到了一个很棒的教程。 链接:https://www.youtube.com/watch?v=quAS1iydq7U

void Solution::nextPermutation(vector<int> &a) {


int k=0;
int n=a.size();
for(int i=0;i<n-1;i++)
{
    if(a[i]<a[i+1])
    {
        k=i;
    }
}

int ele=INT_MAX;
int pos=0;
for(int i=k+1;i<n;i++)
{
    if(a[i]>a[k] && a[i]<ele)
    {
        ele=a[i];pos=i;
    }

}

if(pos!=0)
{

swap(a[k],a[pos]);

reverse(a.begin()+k+1,a.end()); 

}    

}

答案 10 :(得分:0)

  1. 从列表末尾开始遍历。将每个与上一个索引值进行比较。
  2. 如果先前的索引(例如,在索引i-1处的值,认为x小于当前索引(索引i)的值,则从右侧开始对子列表进行排序当前位置i
  3. 从当前位置到结束之间选取一个值,该值刚好高于 x,并将其放在索引i-1处。在从中选择值的索引处,放入x。那就是:

    swap(list[i-1], list[j]) where j >= i, and the list is sorted from index "i" onwards

代码:

public void nextPermutation(ArrayList<Integer> a) {
    for (int i = a.size()-1; i > 0; i--){
        if (a.get(i) > a.get(i-1)){
            Collections.sort(a.subList(i, a.size()));
            for (int j = i; j < a.size(); j++){
                if (a.get(j) > a.get(i-1)) {
                    int replaceWith = a.get(j); // Just higher than ith element at right side.
                    a.set(j, a.get(i-1));
                    a.set(i-1, replaceWith);
                    return;
                }
            }
        }
    }
    // It means the values are already in non-increasing order. i.e. Lexicographical highest
    // So reset it back to lowest possible order by making it non-decreasing order.
    for (int i = 0, j = a.size()-1; i < j; i++, j--){
        int tmp = a.get(i);
        a.set(i, a.get(j));
        a.set(j, tmp);
    }
}

示例:

10 40 30 20 => 20 10 30 40  // 20 is just bigger than 10

10 40 30 20 5 => 20 5 10 30 40 // 20 is just bigger than 10.  Numbers on right side are just sorted form of this set {numberOnRightSide - justBigger + numberToBeReplaced}.

答案 11 :(得分:0)

这对于包含11个字母的字符串足够有效。

// next_permutation example
#include <iostream>     
#include <algorithm>
#include <vector>
using namespace std;

void nextPerm(string word) {
  vector<char> v(word.begin(), word.end());
  vector<string> permvec; // permutation vector
  string perm;
  int counter = 0;  // 
  int position = 0; // to find the position of keyword in the permutation vector

  sort (v.begin(),v.end());

  do {
    perm = "";
    for (vector<char>::const_iterator i = v.begin(); i != v.end(); ++i) {
        perm += *i;
    }
    permvec.push_back(perm); // add permutation to vector

    if (perm == word) {
        position = counter +1; 
    }
    counter++;

  } while (next_permutation(v.begin(),v.end() ));

  if (permvec.size() < 2 || word.length() < 2) {
    cout << "No answer" << endl;
  }
  else if (position !=0) {
    cout << "Answer: " << permvec.at(position) << endl;
  }

}

int main () {
  string word = "nextperm";
  string key = "mreptxen";  
  nextPerm(word,key); // will check if the key is a permutation of the given word and return the next permutation after the key.

  return 0;
}

答案 12 :(得分:-7)

我希望这段代码可能会有所帮助。

int main() {

    char str[100];
    cin>>str;
    int len=strlen(len);
    int f=next_permutation(str,str+len);    
    if(f>0) {
        print the string
    } else {
        cout<<"no answer";
    }
}