Leet Code 刷题记录【3】

125. 验证回文串

连着好几道题一次遍历,这道题也不例外。
说到回文串第一反应就是栈,但考虑空间复杂度,当然是在原来的数组上遍历最好。
这里用到了几个函数:
1、string的大小写转换
单个字符可以这样写tolower(s[0])
整个字符串的话这样写transform(s.begin(),s.end(),s.begin(),::tolower);
参考这里:【用法总结】C++中常用的大小写转换(4种常用方法)
2、判断字符是否是英文字符||数字
用isalnum来判断,类似的还有好几个函数。
可以看这里:C++ isalpha、isalnum、islower、isupper用法

136. 只出现一次的数字

这道题除了骚我也不知道说什么好了。
第一反应是搞一个线性表,每看到一个不一样的数字就加进去,遇到相同的再删掉。这基本上也就比暴力搜要好那么一丢丢。
下面根据Philos的题解来学习一下三种解法的思路,和一些C++的写法。

1、比较优雅地用map暴力搜索
思路很简单,就是建立一个unordered_map,第一位存不同的元素值,第二位存元素出现的个数。遍历一次建立这个map,再遍历map找那个只出现一次的元素。
去官网上看了眼unordered_map的一些用法:
Iterators to elements of unordered_map containers access to both the key and the mapped value. For this, the class defines what is called its value_type, which is a pair class with its first value corresponding to the const version of the key type (template parameter Key) and its second value corresponding to the mapped value (template parameter T):

typedef pair<const Key, T> value_type;

Iterators of a unordered_map container point to elements of this value_type. Thus, for an iterator called it that points to an element of a map, its key and mapped value can be accessed respectively with:

unordered_map<Key,T>::iterator it;
(*it).first;             // the key value (of type Key)
(*it).second;            // the mapped value (of type T)
(*it);                   // the "element value" (of type pair<const Key,T>) 

Naturally, any other direct access operator, such as -> or [] can be used, for example:

it->first;               // same as (*it).first   (the key value)
it->second;              // same as (*it).second  (the mapped value) 

总体上unordered_map的使用更像python里的字典(我知道c++才是鼻祖,我只是先学会的python,这样理解比较方便)。参照下面这一段官方代码,可以理解如何用[]的方式插入数据。

// unordered_map::operator[]
#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{
   
  std::unordered_map<std::string,std::string> mymap;

  mymap["Bakery"]="Barbara";  // new element inserted
  mymap["Seafood"]="Lisa";    // new element inserted
  mymap["Produce"]="John";    // 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值