无重复字符的最长子串(leetcode.3)
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以长度为 3。
class Solution {
public int lengthOfLongestSubstring(String s) {
//也是滑动窗口,不重复时扩充右边界,重复时压缩左边界
Set set = new HashSet();
int len = 0;
int start = 0;
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(!set.contains(ch)){
set.add(ch);
}else{
//int end = s.substring(start, s.length()).indexOf(ch);
//while(start <= end){
// set.remove(s.charAt(start++));
//}
while(set.contains(ch)){
set.remove(s.charAt(start));
start++;
}
//s = s.substring(start, s.length());
set.add(ch);
}
len = Math.max(len, set.size());
}
return len;
}
}
最长回文子串
给你一个字符串 s,找到 s 中最长的回文子串。
示例 1:
输入:s = “babad”
输出:“bab”
解释:“aba” 同样是符合题意的答案。
示例 2:
输入:s = “cbbd”
输出:“bb”
class Solution {
public String longestPalindrome(String s) {
char[] chs = s.toCharArray();
int left = 0, right = 0;
int max1 = 0, max2 = 0, max = 0;
String str1 = "", str2 = "";
for(int i = 0; i < s.length(); i++){
//奇数情况
left = i - 1;
right = i + 1;
while(left >= 0 && right < s.length() && chs[left]==chs[right]){
left--;
right++;
}
int dis1 = right - left - 1;
if(dis1 > max1){
max1 = dis1;
str1 = s.substring(left+1, right);
}
//偶数情况
left = i;
right = i + 1;
while(left >= 0 && right < s.length() && chs[left]==chs[right]){
left--;
right++;
}
int dis2 = right - left - 1;
if(dis2 > max2){
max2 = dis2;
str2 = s.substring(left+1, right);
}
}
return max1 > max2 ? str1 : str2;
}
}
字符串处理1(huaweiOJ.328)
给你两个字符串 t 和 p ,要求从 t 中找到一个和 p 相同的连续子串,并输出该字串第一个字符的下标。
输入
输入文件包括两行,分别表示字符串 t 和 p ,保证 t 的长度不小于 p ,且 t 的长度不超过1000000,p 的长度不超过10000。
输出
如果能从 t 中找到一个和 p 相等的连续子串,则输出该子串第一个字符在t中的下标(下标从左到右依次为1,2,3,…);如果不能则输出”No”;如果含有多个这样的子串,则输出第一个字符下标最小的。
样例
AVERDXIVYERDIAN
RDXI
输出样例
4
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String t = sc.nextLine();
String p = sc.nextLine();
sc.close();
if (t.contains(p)){
System.out.println(t.indexOf(p) + 1);//???为什么要+1
} else {
System.out.println("No");
}
}
}
待编???
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
* Note: 提供的缺省代码仅供参考,可自行根据答题需要进行使用、修改或删除。
*/
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
/**
* OJ考题代码:合法mac地址
*
* @author 命题组
* @since 2020-04-21
*/
public class Main {
/**
* main入口由OJ平台调用
*/
public static void main(String[] args) {
Scanner cin = new Scanner(System.in, StandardCharsets.UTF_8.name());
String macAddress = cin.nextLine();
cin.close();
int result = getMacNum(macAddress);
System.out.println(result);
}
// 待实现函数,在此函数中填入答题代码
private static int getMacNum(String macAddress) {
return 0;
}
}