-
实现strStr()
image.png
思路:暴力匹配:将needle与haystack中所有字串均进行匹配即可
class Solution {
public int strStr(String haystack, String needle) {
int index1 = 0;
int index2 = 0;
if (needle.length() == 0) {
return 0;
} else {
for (int i = 0; i < haystack.length(); i++) {
index1 = i;
while (index1 < haystack.length() && index2 < needle.length()) {
if (haystack.charAt(index1) == needle.charAt(index2)) {
index1++;
index2++;
} else {
index2 = 0;
break;
}
}
if (index2 == needle.length()) {
return i;
} else if (index1 == haystack.length()) {
return -1;
}
}
return -1;
}
}
}
-
搜索插入位置
image.png
思路:当target大于nums[pos]所指元素时pos++,循环结束后的位置即为插入位置(注意在while中要判断pos是否越界)
class Solution {
public int searchInsert(int[] nums, int target) {
int pos = 0;
if (nums.length == 0) {
nums[0] = target;
return 0;
}
while (target > nums[pos]) {
pos++;
if (pos == nums.length) {//注意判断是否越界
return nums.length ;
}
}
return pos;
}
}
-
最大子序和
image.png
思路: