LeetCode Various 3

T3. 无重复字符的最长字串

题目描述:

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

 

思路:

当作队列处理,每次加入相同字符时,需从头开始出对,每次处理最大长度即为最后结果。

 

代码:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
    int ans = 0;
    vector<char> res;
    for(int i = 0; i < s.size(); i++){
        while(count(res.begin(), res.end(), s[i])){
            res.erase(res.begin());
        }
        res.push_back(s[i]);
        int length = res.size();
        ans = max(ans, length);
    }
    return ans;
}
};

 

T6. Z字形变换

题目描述:

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

P   A   H   N
A P L S I I G
Y   I   R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。

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

string convert(string s, int numRows);

 

示例:

输入:s = "PAYPALISHIRING", numRows = 4
输出:"PINALSIGYAHRPI"
解释:
P     I    N
A   L S  I G
Y A   H R
P     I

 

思路:

找规律即可。

 

代码:

class Solution {
public:
    string convert(string s, int numRows) {
        vector<string> res(numRows);
        int x = 2 * numRows - 2, y = 0; 
        if(x == 0) return s;
        string ans = "";
        while(y != numRows) {
            for(int i = 0; i < s.size(); i++) 
                if((i % x == y) || (i + y) % x == 0) res[y] += s[i];
            y++;
        }
        for(int i = 0; i < numRows; i++) 
            ans += res[i];
        return ans;
    }
};

 

posted @ 2022-02-09 12:11  HM-7  阅读(31)  评论(0)    收藏  举报