码迷,mamicode.com
首页 > 其他好文 > 详细

String Permutation

时间:2016-06-05 09:45:39      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5560099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!