首页 > 代码库 > CC150 8.4
CC150 8.4
8.4 Write a method to compute all permutations of a string.
This is a very similar question to CC8.3
static Collection<String> permutations(String s) { if (s == null || s.isEmpty()) return Collections.emptyList(); if (s.length() == 1) return Collections.singletonList(s); Set<String> toReturn = new HashSet<>(); String firstChar = s.substring(0, 1); String otherChars = s.substring(1, s.length()); Collection<String> otherResults = permutations(otherChars); for (String r : otherResults) { Set<String> insertCResults = insertAllPos(firstChar, r); toReturn.addAll(insertCResults); } return toReturn; } private static Set<String> insertAllPos(String c, String toInsert) { Set<String> toReturn = new HashSet<>(); for (int i = 0 ; i <= toInsert.length() ; i ++) { String s = ""; if (i > 0) { s += toInsert.substring(0, i); } s += c; if (i <= toInsert.length()) { s += toInsert.substring(i, toInsert.length()); } toReturn.add(s); } return toReturn; }
CC150 8.4
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。