字符串

3. 无重复字符的最长子串

给定一个字符串,找出不含有重复字符的 最长子串 的长度。

示例:

给定 “abcabcbb” ,没有重复字符的最长子串是 “abc” ,那么长度就是3。

给定 “bbbbb” ,最长的子串就是 “b” ,长度是1。

给定 “pwwkew” ,最长子串是 “wke” ,长度是3。请注意答案必须是一个子串,”pwke” 是 子序列 而不是子串。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char, int> ch;
        int count = 0;
        int i = 0;
        int max = 0;
        int start = 0;


        while(i< s.size())
        {
            //ch中没有重复字母
            if( ch.find(s[i]) == ch.end())
            {
                ch[s[i]] = i;
                ++count;
                ++i;
            }
            //重复字母没在当前计算子串中
            else if(ch[s[i]] < start)
            {
                ch[s[i]] = i;
                ++count;
                ++i;
            }
            //字母重复,更新最值和子串起始位置
            else
            {
                if(count > max)
                    max = count;
                //更新
                count = count-(ch[s[i]] - start);
                start = ch[s[i]] + 1; 


                ch[s[i]] = i;
                ++i;
            }
        }

        if(count > max)
            max = count;

        return max;

    }
};

6. Z字形变换

将字符串 “PAYPALISHIRING” 以Z字形排列成给定的行数:

P A H N
A P L S I I G
Y I R
之后从左往右,逐行读取字符:”PAHNAPLSIIGYIR”

实现一个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);
示例 1:

输入: s = “PAYPALISHIRING”, numRows = 3
输出: “PAHNAPLSIIGYIR”
示例 2:

输入: s = “PAYPALISHIRING”, numRows = 4
输出: “PINALSIGYAHRPI”
解释:

P I N
A L S I G
Y A H R
P I

/*依次将字符存入每行中,按照z型

*/
class Solution {
public:
    string convert(string s, int numRows) {
        std::string *rs = new std::string[numRows];

    int row = 0;
    int flog = 1;
    int len = s.length();
    if (numRows == 1)
        return std::string(s);
    for (int i = 0; i < len; i++)
    {
        rs[row] += s[i];  //0行,1行...n行,n-1行...0行

        if (!row)
            flog = 1;
        else if (row == (numRows - 1))
            flog = -1;
        row += flog;
    }

    std::string result;
    for (int i = 0; i < numRows; i++)
    {
        result += rs[i];
    }

    return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值