rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

2325. 解密消息 #63

Open rocksc30 opened 1 year ago

rocksc30 commented 1 year ago
class Solution {
    public String decodeMessage(String key, String message) {
        Map<Character, Character> map = new HashMap<>();
        int aux = 0;
        for(int i = 0; i < key.length(); i++){

            char c = key.charAt(i);
            if(c == ' '){
                continue;
            }
            if(!map.containsKey(c)){
                map.put(c, (char)('a' + aux));
                aux = (aux + 1) % 26;
            }
        }
        StringBuilder ans = new StringBuilder();
        for(int i = 0; i < message.length(); i++){
            char c = message.charAt(i);
            if(c == ' '){
                ans.append(' ');
            }else{
                ans.append(map.get(c));
            }
        }
        return ans.toString();
    }
}
Ni-Guvara commented 1 year ago
class Solution {
public:
    string decodeMessage(string key, string message) {
        unordered_map<char,char> dic;

        int len = key.size();
        int cnt = 0;

        for(int i = 0; i < len ;i++)
        {
            if( key[i]!=' ' && dic.find(key[i]) == dic.end() )
            {
                dic[key[i]] = 'a' + cnt++; 
            }
        }

        string ret = "";
        for(int i = 0;i < message.length();i++)
        {
            if(message[i] == ' ')
                ret.push_back(message[i]);
            else
                ret.push_back(dic[message[i]]);
        }

        return ret;
    }
};