• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
村雨sup
自己选的路,跪着也要走完 XD
博客园    首页    新随笔    联系   管理    订阅  订阅
Leetcode 784

//这代码可真丑陋,但我学到了两点1:char和string可以无缝互相转换2:char可以直接加减数字进行转换string不行

class Solution {
public:
    vector<string> letterCasePermutation(string S) {
        vector<string> res;
        string add;
        DFS(res,S,0,add);
        return res;
    }
    
    char func(char temp){
        if(temp >= 97&&temp <= 122){
            temp -= 32;
        }
        else if(temp <= 90&&temp >= 65){
            temp += 32;
        }
        return temp;
    }
    
    void DFS(vector<string>& res,string s,int pos,string add){
        if(add.size() == s.size()){
            res.push_back(add);
        }
        else{
            for(int i=pos;i < s.size();i++){
                char t = s[i];   
                if(t >= 48 && t <= 57){
                    add += s[i];
                }
                else{
                    string temp = add;
                    temp += func(t);
                    DFS(res,s,i+1,temp);
                    add += s[i];
                }
            }
        if(add.size() == s.size()){ // 这里又加了个是因为害怕最后一个是数字
            res.push_back(add);
        }
            
        }
    }
};

 好方法:很简洁

class Solution {
public:
    vector<string> letterCasePermutation(string S) {
        vector<string> res;
        helper(S, 0, res);
        return res;
    }
    void helper(string& s, int pos, vector<string>& res) {
        if (pos == s.size()) {
            res.push_back(s);
            return;
        }
        helper(s, pos + 1, res);
        if (s[pos] > '9') {
            s[pos] ^= 32;
            helper(s, pos + 1, res);
        }
    }
};

 

posted on 2018-11-04 21:36  村雨sup  阅读(105)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3