1、长按键入
//你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。 // // 你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。 // // // // 示例 1: // // 输入:name = "alex", typed = "aaleex" //输出:true //解释:'alex' 中的 'a' 和 'e' 被长按。 // // // 示例 2: // // 输入:name = "saeed", typed = "ssaaedd" //输出:false //解释:'e' 一定需要被键入两次,但在 typed 的输出中不是这样。 // // // 示例 3: // // 输入:name = "leelee", typed = "lleeelee" //输出:true // // // 示例 4: // // 输入:name = "laiden", typed = "laiden" //输出:true //解释:长按名字中的字符并不是必要的。 // // // // // 提示: // // // name.length <= 1000 // typed.length <= 1000 // name 和 typed 的字符都是小写字母。 // // // // // // Related Topics 双指针 字符串
今天的这两道题就是需要多考虑一些情况,其他都没有什么技巧的,主要把握双指针的基本解题思路就没有太大的问题
public boolean isLongPressedName(String name, String typed) {
int start_a = 0;
int start_b = 0;
int length_a = name.length();
int length_b = typed.length();
while(start_a<length_a && start_b<length_b){
if(name.charAt(start_a)==typed.charAt(start_b)){
int m = 0;
int n = 0;
//要保证不会超出字符串范围
while(start_a+1<length_a && name.charAt(start_a)==name.charAt(start_a+1)){
start_a++;
m++;
}
while(start_b+1<length_b && typed.charAt(start_b)==typed.charAt(start_b+1)){
start_b++;
n++;
}
//遇到相同的字母,要保证typed中的字母的数量要多余name中的数量
if(m>n){
return false;
}
start_a++;
start_b++;
}else{
return false;
}
}
//当其中有一个字符串没有遍历完的时候,那么肯定不符合题设情况
if(start_a < length_a || start_b < length_b){
return false;
}
return true;
}
2、最大升序子数组和
//给你一个正整数组成的数组 nums ,返回 nums 中一个 升序 子数组的最大可能元素和。 // // 子数组是数组中的一个连续数字序列。 // // 已知子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,若对所有 i(l <= i < r),numsi < numsi //+1 都成立,则称这一子数组为 升序 子数组。注意,大小为 1 的子数组也视作 升序 子数组。 // // // // 示例 1: // // //输入:nums = [10,20,30,5,10,50] //输出:65 //解释:[5,10,50] 是元素和最大的升序子数组,最大元素和为 65 。 // // // 示例 2: // // //输入:nums = [10,20,30,40,50] //输出:150 //解释:[10,20,30,40,50] 是元素和最大的升序子数组,最大元素和为 150 。 // // // 示例 3: // // //输入:nums = [12,17,15,13,10,11,12] //输出:33 //解释:[10,11,12] 是元素和最大的升序子数组,最大元素和为 33 。 // // // 示例 4: // // //输入:nums = [100,10,1] //输出:100 // // // // // 提示: // // // 1 <= nums.length <= 100 // 1 <= nums[i] <= 100 // // Related Topics 双指针
public int maxAscendingSum(int[] nums) {
int max = Integer.MIN_VALUE;
int start = 0;
int end = 0;
while(start<nums.length && end<nums.length){
int sum = nums[start];
//始终保持end和start中间相差1
end = start+1;
//出现单个数字的时候
if(start == nums.length-1 || nums[end]<=nums[end]){
if(max<sum){
max = sum;
}
}
while (end < nums.length && nums[end]>nums[start]){
sum += nums[end];
start++;
end++;
}
if(max<sum){
max = sum;
}
start = end;
}
return max;
}