描述
给定一个字符串S,我们可以将其中所有的字符任意切换大小写并得到一个新的字符串。将所有可生成的新字符串以一个列表的形式输出。
样例
样例 1:
输入: S = "a1b2"
输出: ["a1b2", "a1B2", "A1b2", "A1B2"]
样例 2:
输入: S = "3z4"
输出: ["3z4", "3Z4"]
样例 3:
输入: S = "12345"
输出: ["12345"]
代码
public class Solution4 {
public static void main(String[] args) {
String str = "1abcjmk";
/*String str2= "adawd123";
Queue<String> queue = new LinkedList<>();
queue.offer(str);
queue.offer(str2);
System.out.println(JSON.toJSONString(queue));
List list = new LinkedList<>(queue);
System.out.println(JSON.toJSONString(list));*/
System.out.println(JSON.toJSONString(letterCasePermutation(str)));
System.out.println(JSON.toJSONString(letterCasePermutation2(str)));
}
/使用set 属性 不能有重复key值,但效率低 有重复值插入但情况
public static List<String> letterCasePermutation2(String S) {
// write your code here
char[] charArr = S.toCharArray(),withinArr;
int len = charArr.length,withinLen;
Set<String> setStrs = new HashSet<String>();
setStrs.add(S);
for (int i = 0; i < len; i++) {
//如果当前char为数字返回true
if (Character.isDigit(charArr[i])){continue;}
withinLen = setStrs.size();
Object[] arrrw = setStrs.toArray();
for (int j = 0; j < withinLen; j++) {
String str = String.valueOf(arrrw[j]);
withinArr = str.toCharArray();
withinArr[i] = Character.toUpperCase(withinArr[i]);
setStrs.add(new String(withinArr));
withinArr[i] = Character.toLowerCase(withinArr[i]);
setStrs.add(new String(withinArr));
}
}
return new LinkedList<>(setStrs);
}
//使用队列 避免了重复插入的情况 对比上面的方法效率高。
public static List<String> letterCasePermutation(String S) {
// write your code here
char[] charArr = S.toCharArray(),withinArr;
int len = charArr.length,withinLen;
Queue<String> queue = new LinkedList<>();
queue.add(S);
for (int i = 0; i < len; i++) {
//如果当前char为数字返回true
if (Character.isDigit(charArr[i])){continue;}
withinLen = queue.size();
for (int j = 0; j < withinLen; j++) {
//取出队列第一条数据并返回
String firstData = queue.poll();
withinArr = firstData.toCharArray();
//每个字母节点有2中情况
withinArr[i] = Character.toLowerCase(withinArr[i]);
queue.add(new String(withinArr));
withinArr[i] = Character.toUpperCase(withinArr[i]);;
queue.add(new String(withinArr));
}
}
return new LinkedList<>(queue);
}
}