String 的简单OJ题

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;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北海有初拥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值