1.字符串中的第一个唯一字符
class Solution {
public:
int firstUniqChar(string s)
{
//统计次数
int count[26] = {0};
for(auto ch : s)
{
count[ch-'a']++;
}
for(size_t i = 0;i < s.size();++i)
{
if(count[s[i] - 'a' ]== 1)
{
return i;
}
}
return -1;
}
};
2.仅仅反转字母
class Solution
{
public:
//判断是不是字母
bool isLetter(char ch)
{
if(ch >= 'a' && ch <= 'z')
return true;
if(ch >= 'A' && ch <= 'Z')
return true;
return false;
}
string reverseOnlyLetters(string S)
{
if(S.empty())
return S;
size_t begin = 0, end = S.size()-1;
while(begin < end)
{
while(begin < end && !isLetter(S[begin]))
++begin;
while(begin < end && !isLetter(S[end]))
--end;
swap(S[begin], S[end]);
++begin;
--end;
}
return S;
}
};
3.字符串最后一个单词的长度
#include<iostream>
#include<string>
using namespace std;
int main()
{
string line;
// 不要使用cin>>line,因为会它遇到空格就结束了
// while(cin>>line)
while(getline(cin, line))
{
size_t pos = line.rfind(' ');
cout<<line.size()-pos-1<<endl;
}
return 0;
}
4.验证回文串
class Solution {
public:
bool isLetterOrNumber(char ch)
{
return (ch>='0'&&ch <='9')
|| (ch >='a'&& ch <='z')
|| (ch>='A' && ch <= 'Z');
}
bool isPalindrome(string s)
{
for(auto& ch : s)
{
if(ch >='A' && ch <= 'Z')
{
ch += 32;
}
}
int begin = 0 , end = s.size()-1;
while(begin < end)
{
while(begin < end && !isLetterOrNumber(s[begin]))
++begin;
while(begin < end && !isLetterOrNumber(s[end]))
--end;
if(s[begin] != s[end])
{
return false;
}
else
{
++begin;
--end;
}
}
return true;
}
};