首页 > 代码库 > 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