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"; //