码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 412. Fizz Buzz

时间:2020-05-30 12:43:38      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:字符串连接   first   map   字符串   ping   tco   store   span   second   

技术图片

 

 使用散链表的字符串连接法。

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> ans;

        //Hash map to store all fizzbuzz mappings.
        map<int, string> fizzBuzzDict = {
            {3, "Fizz"},
            {5, "Buzz"} 
        };
    
        for (int num = 1; num <= n; ++num)
        {
            string numAnsStr = "";

            for (auto key : fizzBuzzDict)
            {
                //If the num is divisible by key,
                //then add the corressponding string mapping to current numAnsStr
                if (num % key.first == 0)
                    numAnsStr += key.second;
            }
            //Not divisible by 3 or 5, add the number
            if (numAnsStr == "")
                numAnsStr += to_string(num);
            // Append the current answer str to the ans list
            ans.push_back(numAnsStr);
        }
        return ans;
    }
};

 

LeetCode 412. Fizz Buzz

标签:字符串连接   first   map   字符串   ping   tco   store   span   second   

原文地址:https://www.cnblogs.com/ZSY-blog/p/12991491.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!