是否有任何预先构建的方法可以在JavaScript中查找给定字符串的所有排列? [英] Is there any pre-built method for finding all permutations of a given string in JavaScript?

查看:95
本文介绍了是否有任何预先构建的方法可以在JavaScript中查找给定字符串的所有排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript世界的新手。正如标题所提到的,我想知道JavaScript中是否有任何预先构建的方法来查找给定字符串的所有可能的排列。

I'm a newbie to the JavaScript world. As the title mentions, I want to know whether there is any pre-built method in JavaScript to find all possible permutations of a given string.

例如,给定输入:

the

期望输出:

the
teh
eht
eth
het
hte


推荐答案

没有预先构建,但是可以编写这样的函数..这是使用两个函数的一种相对简单的方法:

No pre-built, but writing such function is possible.. here is one relatively simple way using two functions:

function FindAllPermutations(str, index, buffer) {
    if (typeof str == "string")
        str = str.split("");
    if (typeof index == "undefined")
        index = 0;
    if (typeof buffer == "undefined")
        buffer = [];
    if (index >= str.length)
        return buffer;
    for (var i = index; i < str.length; i++)
        buffer.push(ToggleLetters(str, index, i));
    return FindAllPermutations(str, index + 1, buffer);
}

function ToggleLetters(str, index1, index2) {
    if (index1 != index2) {
        var temp = str[index1];
        str[index1] = str[index2];
        str[index2] = temp;
    }
    return str.join("");
}

用法:

var arrAllPermutations = FindAllPermutations("the");

实时测试案例: http://jsfiddle.net/yahavbr/X79vz/1/

这只是基本的实现,它不会删除重复项,也没有优化。但是对于小字符串你不会有任何问题,添加时间测量就像上面的测试用例一样,看看你的合理限制是什么。

This is just basic implementation, it won't remove duplicates and has no optimization. However for small strings you won't have any problem, add time measure like in the above test case and see what's your reasonable limit.

这篇关于是否有任何预先构建的方法可以在JavaScript中查找给定字符串的所有排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆