1、LeetCode784 字母大小写全排列
生活随笔
收集整理的這篇文章主要介紹了
1、LeetCode784 字母大小写全排列
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
LeetCode784 字母大小寫全排列
給定一個(gè)字符串S,通過將字符串S中的每個(gè)字母轉(zhuǎn)變大小寫,我們可以獲得一個(gè)新的字符串。返回所有可能得到的字符串集合。
示例:
輸入:S = “a1b2”
輸出:[“a1b2”, “a1B2”, “A1b2”, “A1B2”]
輸入:S = “3z4”
輸出:[“3z4”, “3Z4”]
輸入:S = “12345”
輸出:[“12345”]
文章目錄
- LeetCode784 字母大小寫全排列
- 回溯法
- 深度優(yōu)先遍歷
回溯法
class Solution {List<String> ans=new LinkedList<>();public List<String> letterCasePermutation(String s) {char[] chs=s.toCharArray(); help(chs,0);return ans;}public void help(char[] chs,int start){ans.add(new String(chs));for(int i=start;i<chs.length;i++){if(chs[i]>='0' && chs[i]<='9'){continue;}else if(chs[i]>='a' &&chs[i]<='z'){//當(dāng)前小寫字母,要轉(zhuǎn)變?yōu)榇髮懽帜?#xff0c;所以減32chs[i]-=32;help(chs,i+1);//回溯chs[i]+=32;}else{//當(dāng)前大寫字母,要轉(zhuǎn)變?yōu)樾懽帜?#xff0c;所以加32chs[i]+=32;help(chs,i+1);//回溯chs[i]-=32;}}} }深度優(yōu)先遍歷
class Solution {List<String> ans=new LinkedList<>();public List<String> letterCasePermutation(String s) {char[] chs=s.toCharArray(); help(chs,0,chs.length);return ans;}public void help(char[] chs,int start,int len){if(start==len){ans.add(new String(chs));return;}help(chs,start+1,len);if(Character.isLetter(chs[start])){//start位置如果是小寫則變成大寫,大寫變成小寫chs[start]^=32;help(chs,start+1,len);}} }總結(jié)
以上是生活随笔為你收集整理的1、LeetCode784 字母大小写全排列的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 5、计算机网络物理层和数据链路层
- 下一篇: 6、计算机网络层