日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

784. Letter Case Permutation

發(fā)布時間:2023/12/10 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 784. Letter Case Permutation 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

  • 1 題目理解
  • 2 回溯

1 題目理解

Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.

Return a list of all possible strings we could create. You can return the output in any order.
輸入:字符串
輸出:字符串可能的變形
規(guī)則:每一個位置上的字符都可能變?yōu)榇髮懟蛘咝憽7亲帜傅谋3衷帜浮?/p>

Example 1:

Input: S = “a1b2”
Output: [“a1b2”,“a1B2”,“A1b2”,“A1B2”]

2 回溯

每個字符位,可能是大寫,也可能是小寫。回溯遞歸即可實現(xiàn)。

class Solution {private String S;private List<String> answer;public List<String> letterCasePermutation(String S) {this.S = S;answer = new ArrayList<String>();dfs(0,"");return answer;}private void dfs(int index,String str){if(index >= S.length()){answer.add(str);}else{char ch = S.charAt(index);if(ch>='0' && ch<='9'){dfs(index+1,str+ch);}else if(ch>='A' && ch<='Z'){dfs(index+1,str+ch);ch += 32;dfs(index+1,str+ch);}else if(ch>='a' && ch<='z'){dfs(index+1,str+ch);ch -= 32;dfs(index+1,str+ch);}}} }

第二種方式:可以使用二進制位。對于每一位有兩種選擇的情況可以用二進制位來解決。

class Solution {public List<String> letterCasePermutation(String S) {int charCount = 0;for(char ch : S.toCharArray()){if(Character.isLetter(ch)){charCount++;}}List<String> answer = new ArrayList<String>();int max = (1<<charCount)-1;for(int i = 0;i<=max;i++){int j = 0;StringBuilder s = new StringBuilder();for(char ch : S.toCharArray()){if(Character.isLetter(ch)){if(((i>>j) &1)==1){s.append(Character.toLowerCase(ch));}else{s.append(Character.toUpperCase(ch));}j++;}else{s.append(ch);}}answer.add(s.toString());}return answer;} }

此處用StringBuilder比String快了不好。

總結

以上是生活随笔為你收集整理的784. Letter Case Permutation的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。