数组和字符串
常用操作
1、转化为数组
public class Main {
public static void main(String[] args) {
String s = "Hello World";
char[] str = s.toCharArray();
str[5] = ',';
System.out.println(str);
}
}
2、字符串拼接:StringBuilder
public class Main {
public static void main(String[] args) {
int n = 10000;
StringBuilder str = new StringBuilder();
for (int i = 0; i < n; i++) {
str.append("hello");
}
String s = str.toString();
}
}
练习题1:实现 strStr()
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
题解:
class Solution {
public int strStr(String haystack, String needle) {
int hLen = haystack.length();
int nLen = needle.length();
if(nLen == 0 || haystack.equals(needle)){
return 0;
}
for (int i = 0; i < hLen - nLen+1; i++){
if (haystack.substring(i,i+nLen).equals(needle)){
return i;
}
}
return -1;
}
}
练习题2 旋转数组
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]
示例 2:
输入: [-1,-100,3,99] 和 k = 2
输出: [3,99,-1,-100]
解释:
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]
说明:
尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的 原地 算法。
题解
class Solution {
public void rotate(int[] nums, int k) {
int length = nums.length;
int[] tempNums = new int[length];
for (int i = 0;i<length;i++ ){
tempNums[(i+k)%length]=nums[i];
}
for (int j = 0;j < length;j ++){
nums[j]=tempNums[j];
}
}
}