Home > Web Front-end > JS Tutorial > body text

Algorithmic analysis of full arrangement of strings in js

不言
Release: 2018-07-20 10:58:30
Original
2390 people have browsed it

这篇文章给大家介绍的内容是关于js中字符串的全排列的算法解析,有着一定的参考价值,有需要的朋友可以参考一下。

题目描述

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

分析

没啥好分析的了,这个题不会,上网查的思路,大概就是:

abc分化为abc、bac、cba(这是0和0交换、0和1交换、0和2交换

第一步得出的abc分化为abc、acb(这是1和1交换、1和2交换

第一步得出的bac分化为bac、bca(这是1和1交换、1和2交换

第一步得出的cba分化为cba、cab(这是1和1交换、1和2交换

代码实现

function Permutation(str)
{
    if(str === null || str === "")
        return [];
    var res = [];
    var index = 0;
    
    step(str.split(""), index, res);
    
    return res.sort();
}

function step(strArr, cur, res) {
    if(cur === strArr.length-1){
        var i = 0, str = "";
        while(i < strArr.length){
            str += strArr[i++];
        }
        res.push(str);
    }
    
    for(var i = cur;i < strArr.length;i++) {
        if(strArr[i] === strArr[cur] && i !== cur)
            continue;
        swap(strArr, i, cur);
        step(strArr, cur+1, res);
        swap(strArr, i, cur);
    }
}

function swap(arr, a, b) {
    var temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
}
Copy after login

相关推荐:

JavaScript中Object.defineProperty()方法的解析

vue-cli的单元测试的示例解析

React的使用:React组件内部的状态管理

The above is the detailed content of Algorithmic analysis of full arrangement of strings in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!