寻找符合要求的最长子串od机试java
时间: 2023-12-24 20:01:14 浏览: 74
寻找符合要求的最长子串od机试java,可以通过遍历字符串的方式来寻找。首先,我们可以使用一个指针来遍历整个字符串,同时使用另外两个指针来记录符合要求的子串的起始位置和结束位置。然后,我们可以使用一个哈希表来记录每个字符出现的次数,以便判断是否满足条件。
当我们遍历到一个字符时,我们可以将其加入哈希表,并判断哈希表中是否包含符合条件的字符。如果包含,我们可以更新子串的结束位置,并计算当前子串的长度。同时,我们可以更新最长子串的起始位置和结束位置,并记录最长子串的长度。
在遍历结束后,我们就可以得到符合要求的最长子串od机试java。这个方法的时间复杂度为O(n),其中n是字符串的长度。因此,我们可以通过这种方法高效地找到符合要求的最长子串。
相关问题
华为od机试 2023】 最长的密码(c++ java javascript python)
题目描述:
给定一个字符串 s ,请你找出其中最长的不含重复字符的子串长度。
示例:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
思路分析:
用一个 hash 表存储每个字符最后一次出现的位置。遍历字符串,记录当前子串的起始位置 start 和当前位置 i,当遇到重复字符时,更新 start 的位置。最后更新最长子串的长度。
代码实现:
Python:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
hash_map = {}
res = 0
start = 0
for i in range(len(s)):
if s[i] in hash_map and hash_map[s[i]] >= start:
start = hash_map[s[i]] + 1
hash_map[s[i]] = i
res = max(res, i - start + 1)
return res
Java:
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] hash_map = new int[256];
int res = 0;
int start = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (hash_map[c] >= start) {
start = hash_map[c] + 1;
}
hash_map[c] = i;
res = Math.max(res, i - start + 1);
}
return res;
}
}
C++:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> hash_map(256, -1);
int res = 0;
int start = 0;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (hash_map[c] >= start) {
start = hash_map[c] + 1;
}
hash_map[c] = i;
res = max(res, i - start + 1);
}
return res;
}
};
总结:
这道题考察了字符串的基础操作和 hash 表的使用。通过本题的练习,可以在实际开发中更加熟练地使用 hash 表,提高代码效率和可读性。
阅读全文
相关推荐









