LeetCode 784. Letter Case Permutation
阿新 • • 發佈:2018-12-13
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. Examples: Input: S = "a1b2" Output: ["a1b2", "a1B2", "A1b2", "A1B2"] Input: S = "3z4" Output: ["3z4", "3Z4"] Input: S = "12345" Output: ["12345"] Note: S will be a string with length at most 12. S will consist only of letters or digits.
分析:每個字母可大寫可小寫,用0,1代表該字母的大小寫的狀態,1為大寫。若字串為a1b2,包含兩個字母,則兩個字母所有的狀態組合為{00,01,10,11},將列舉狀態看作二進位制數,則化為十進位制為{0,1,2,3},這樣問題就能很好地被解決了。
#include<iostream> #include<vector> #include<string> #include<bitset> #include<math.h> using namespace std; vector<string> letterCasePermutation(string& s) { vector<string> ans; vector<int> letterPos; int mark = 1,size = s.size(); if(size == 0 ) return ans; for(int i = 0; i < size; i++) { if(isalpha(s[i])) { s[i] = tolower(s[i]); mark *= 2; letterPos.push_back(i); } } for(int i = 0; i < mark; i++) { int t = i; string ts = s; for(int j = 0;j < letterPos.size(); j++) { //cout << t << " " << j << " " << (t >> j) % 2 << endl; if((t >> j) % 2 == 1) { ts[letterPos[letterPos.size() - 1 - j]] = toupper(s[letterPos[letterPos.size() - 1 - j]]); } //ts[letterPos[j]] = (t >> j) % 2 == 1 ? toupper(s[letterPos[j]]) : s[letterPos[j]]; } cout << ts << endl; ans.push_back(ts); } return ans; } int main() { string s; s = "a1b2"; vector<string> ans = letterCasePermutation(s); //for(int i = 0;i < ans.size(); i++) cout << ans[i] << endl; }