1. 7
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
分析见这里
解答如下:
public class SetMatrixZero {
public void SetMatrixToZero (int [][] matrix) {
int height = matrix.length;
if (height == 0) return;
int width = matrix[0].length;
if (matrix[0][0] == 0) {
matrix[0][0] = 4; // 4 means, column 0 and row 0 should both be set to 0.
} else {
for (int i = 1; i < width; ++i) {
if (matrix[0][i] == 0) {
matrix[0][0] = 2;
break;
}
}
for (int i = 1; i < height; ++i) {
if (matrix[i][0] == 0) {
matrix[0][0] = 3;
break;
}
}
}
// till now, matrix[0][0] will have 4 values;
// 4: column 0 and row 0 should both be set to 0.
// 1: neither of column 0 and row 0 should be set to 0.
// 2: row 0 should be set to 0.
// 3: column 0 should be set to 0.
for (int i = 1; i < height; ++i) {
for (int j = 1; j < width; ++j) {
if (matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for (int i = 1; i < height; ++i) {
for (int j = 1; j < width; ++j) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
if (matrix[0][0] == 2 || matrix[0][0] == 4 ) {
for (int i = 1; i < width; ++i)
matrix[0][i] = 0;
}
if (matrix[0][0] == 3 || matrix[0][0] == 4) {
for (int i = 1; i < height; ++i)
matrix[i][0] = 0;
}
if(matrix[0][0] > 1) matrix[0][0] = 0;
return;
}
void printMatrix(int[][] m) {
int height = m.length;
if (height == 0) return;
int width = m[0].length;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < height; ++j) {
System.out.print(m[i][j] + " ");
}
System.out.println("");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SetMatrixZero smz = new SetMatrixZero ();
int[][] input_mat = {{1,1,0},{1,0,1},{1,1,1}};
smz.printMatrix(input_mat);
smz.SetMatrixToZero(input_mat);
smz.printMatrix(input_mat);
}
}
1.8
题目如下:
Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring ( i.e., “waterbottle” is a rotation of “erbottlewat”).
分析如下:
思路还是很巧妙的
1. xy + xy is a string, xyxy.
2. xy is a substring of xyxy.
3. yx is a substring of xyxy, too.
解答如下:
public class IsStr1RotationOfStr2 {
public boolean isSubstring(String str1, String str2) {
return (str1.indexOf(str2) != -1);
}
public boolean isAnyRotation(String str1, String str2) {
if (str2.length() != str2.length())
return false;
String newStr = str1 + str1;
return isSubstring(newStr, str2);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str1 = "waterbottle";
String str2 = "erbottlewat";
IsStr1RotationOfStr2 isrs = new IsStr1RotationOfStr2();
if (isrs.isAnyRotation(str1, str2))
System.out.println("Is Rotated");
}
}