String Permutation

Posted YuriFLAG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了String Permutation相关的知识,希望对你有一定的参考价值。

Given a string, find all permutations of it without duplicates.

Example

Given "abb", return ["abb", "bab", "bba"].

Given "aabb", return ["aabb", "abab", "baba", "bbaa", "abba", "baab"].

思路:permutation 标准的解题步骤:递归 + 回溯。 StringBuilder 有一个删除某一位置字符的函数deleteCharAt(index).

 1 public class Solution {
 2     /**
 3      * @param str a string
 4      * @return all permutations
 5      */
 6     public List<String> stringPermutation2(String str) {
 7        List<String> result = new ArrayList<>();
 8 
 9         char[] ch = str.toCharArray();
10         Arrays.sort(ch);
11         boolean[] visited = new boolean[ch.length];
12         StringBuilder builder = new StringBuilder();
13         helper(result, builder, ch, visited);
14         return result;
15     }
16 
17     private void helper(List<String> result, StringBuilder builder, char[] ch, boolean[] visited) {
18         if (builder.length() == ch.length) {
19             String s = builder.toString();
20             result.add(s);
21             return;
22         }
23 
24         for (int i = 0; i < ch.length; i++) {
25             if (visited[i] || i != 0 && ch[i] == ch[i - 1] && visited[i - 1] == false) {
26                 continue;
27             }
28 
29             visited[i] = true;
30             builder.append(ch[i]);
31             helper(result, builder, ch, visited);
32             builder.deleteCharAt(builder.length() - 1);
33             visited[i] = false;
34         }
35     }
36 }

 

以上是关于String Permutation的主要内容,如果未能解决你的问题,请参考以下文章

Activity 类型的方法 managedQuery(Uri, String[], String, String[], String) 已弃用

C# String与string的区别

Scala RDD[(String,String)] 到 RDD[String]

在JS中String 和string啥区别?

Android String[] string = new String[]{““,““}

string容器