给定一个字符串S
,通过将字符串S
中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
示例:
输入:S = "a1b2"
输出:["a1b2", "a1B2", "A1b2", "A1B2"]
输入:S = "3z4"
输出:["3z4", "3Z4"]
输入:S = "12345"
输出:["12345"]
提示:
S
的长度不超过12
。S
仅由数字和字母组成。
1.回溯
Python:
class Solution:
def letterCasePermutation(self, s: str) -> List[str]:
def backtrace(lis, i):
if i == len(lis):
result.append(''.join(lis))
return
if lis[i].isdigit():
backtrace(lis, i+1)
else:
backtrace(lis, i+1)
if lis[i].isupper():
lis[i] = lis[i].lower()
backtrace(lis, i+1)
lis[i] = lis[i].upper()
else:
lis[i] = lis[i].upper()
backtrace(lis, i+1)
lis[i] = lis[i].lower()
result = []
lis = list(s)
backtrace(lis, 0)
return result
Java:
class Solution {
public List<String> letterCasePermutation(String s) {
List<String> result = new ArrayList<>();
char[] ch = s.toCharArray();
backtrace(result, ch, 0);
return result;
}
public void backtrace(List<String> result, char[] ch, int i)
{
if( i == ch.length)
{
result.add(String.valueOf(ch));
return;
}
if(Character.isDigit(ch[i]))
backtrace(result, ch, i+1);
else
{
backtrace(result, ch, i+1);
if(Character.isUpperCase(ch[i]))
{
ch[i] = Character.toLowerCase(ch[i]);
backtrace(result, ch, i+1);
ch[i] = Character.toUpperCase(ch[i]);
}
else
{
ch[i] = Character.toUpperCase(ch[i]);
backtrace(result, ch, i+1);
ch[i] = Character.toLowerCase(ch[i]);
}
}
}
}
留言