C++中常见的string类题目
翻转字符串
leetcode344题: 翻转字符串
思路: 双指针,交换头尾两个指针所指的两个位置的值,指针向中间移动一个位置。重复以上操作,直到两个指针指向同一位置。
class Solution {
public:
void reverseString(vector<char>& s) {
if(s.empty())
return;
size_t start=0;
size_t end=s.size()-1;
while(start<end){
swap(s[start],s[end]);
++start;
--end;
}
}
};
字符串中的第一个唯一字符
leetcode387题: 字符串中的第一个唯一字符
思路: 统计字符串中每个字符出现的次数并储存在数组中,再按照字符串中字符的顺序寻找只出现一次的字符。
class Solution {
public:
int firstUniqChar(string s) {
if(s.empty())
return -1;
int count[256]={
0};
for(int i=0;i<s.size();++i)
count[s[i]]+=1;
for(int i=0;i<s.size