笔试题目
给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。
方法一暴力解法
class Solution {
public void rotate(int[][] matrix) {
int length = matrix.length;//矩阵的长度
int [][] temp = new int[length][length];
//这里注意,将原数组的第i行复制给第n - i列
//这里需要注意的是角标的变化
//行列 原数组行列 i j
//02-----00 2 0
//12-----01 2 1
//22-----02 2 2
//01-----10 2 0
//11-----11 2 1
//21-----21 2 2
//这里可以看出,将要填充的数组与已有数组的关系
//ji --- length - i - 1
for (int i = length - 1; i >= 0; i--) {
for (int j = 0; j < length; j++) {
temp[j][i] = matrix[length - i - 1][j];
}
}
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
matrix[i][j] = temp[i][j];
}
}
}
}
方法二
先进行一个对角线的变化,在进行一个左右对称的变化
class Solution {
public void rotate(int[][] matrix) {
//这种方法是将数组在原数组进行两次操作,按照对角线操作,然后顺时针就左右进行交换就能都到结果了
int n = matrix.length;
for (int i = 0; i < n; i ++) {
for (int j = 0; j < i; j ++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n / 2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n - j - 1];
matrix[i][n - j - 1] = temp;
}
}
}
}
计算字符串中子串的出现次数(java)
方法一:
使用replace方法和contains方法
统计原字符串的长度,然后新建一个空的字符串,用来接收要统计的字符串在原字符串中替换为空串后的串,然后运用数学公式就可以得出结果
public static int Count(String str,String temp) {
int old_length = str.length();
String replace = "";
if (str.contains(temp)) {
replace = str.replace(temp,"");
}
return (old_length - replace.length()) / temp.length();
}
方法二
使用indexOf,首先indexOf的两种用法
一个参数,就是代表从下标0开始,第一次出现的次数
String str = "aidfjakfj";
System.out.println(str.indexOf("a")); //0
两个参数,第一个字符串,第二个开始的下标
System.out.println(str.indexOf("a",3));//5
记住如果没有返回的结果是-1。
public static int getCount(String str,String substr){
int count = 0;//count用来接收子字符串substr在字符串str中出现的次数
int i = 0;
while(str.indexOf(substr,i) != -1) {
count++;
i=str.indexOf(substr, i)+substr.length();
}
return count;
}
方法三
使用subString,str.substring(indexStart,indexEnd)表示:截取方法调用者(即str)的从indexStart到indexEnd(包括indexStart,不包括indexEnd;即含头不含尾、或左闭右开区间内的子字符串)。左闭右开!!!!!
public static int getMaches(String str,String substr){
int count = 0;
//开始循环统计,加的长度一定是最后再加上一位,左闭右开!!!!
for(int i=0;i<str.length()+1-substr.length();i++) {
if(str.substring(i, substr.length()+i).equals(substr)) {
count++;
}
}
return count;
}