题目:
解答:
import java.util.Scanner;
// 1:无需package
// 2: 类名必须Main, 不可修改
public class Main {
public static void main(String[] args) {
// Scanner scan = new Scanner(System.in);
// //在此输入您的代码...
// scan.close();
String str = "VLPWJVVNNZSWFGHSFRBCOIJTPYNEURPIGKQGPSXUGNELGRVZAGSDLLOVGRTWEYZKKXNKIRWGZWXWRHKXFASATDWZAPZRNHTNNGQFZGUGXVQDQAEAHOQEADMWWXFBXECKAVIGPTKTTQFWSWPKRPSMGABDGMGYHAOPPRRHKYZCMFZEDELCALTBSWNTAODXYVHQNDASUFRLYVYWQZUTEPFSFXLTZBMBQETXGXFUEBHGMJKBPNIHMYOELYZIKHZYZHSLTCGNANNXTUJGBYKUOJMGOGRDPKEUGVHNZJZHDUNRERBUXFPTZKTPVQPJEMBHNTUBSMIYEGXNWQSBZMHMDRZZMJPZQTCWLRZNXOKBITTPSHEXWHZXFLWEMPZTBVNKNYSHCIQRIKQHFRAYWOPGMHJKFYYBQSDPOVJICWWGGCOZSBGLSOXOFDAADZYEOBKDDTMQPAVIDPIGELBYMEVQLASLQRUKMXSEWGHRSFVXOMHSJWWXHIBCGVIFGWRFRFLHAMYWYZOIQODBIHHRIIMWJWJGYPFAHZZWJKRGOISUJCEKQKKPNEYCBWOQHTYFHHQZRLFNDOVXTWASSQWXKBIVTKTUIASKPEKNJFIVBKOZUEPPHIWLUBFUDWPIDRJKAZVJKPBRHCRMGNMFWWCGZAXHXPDELTACGUWBXWNNZNDQYYCIQRJCULIEBQBLLMJEUSZPRWHHQMBIJWTQPUFNAESPZHAQARNIDUCRYQAZMNVRVZUJOZUDGSPFGAYBDEECHUXFUZIKAXYDFWJNSAOPJYWUIEJSCORRBVQHCHMRJNVIPVEMQSHCCAXMWEFSYIGFPIXNIDXOTXTNBCHSHUZGKXFECLYZBAIIOTWLREPZISBGJLQDALKZUKEQMKLDIPXJEPENEIPWFDLPHBQKWJFLSEXVILKYPNSWUZLDCRTAYUUPEITQJEITZRQMMAQNLNDQDJGOWMBFKAIGWEAJOISPFPLULIWVVALLIIHBGEZLGRHRCKGFLXYPCVPNUKSWCCGXEYTEBAWRLWDWNHHNNNWQNIIBUCGUJYMRYWCZDKISKUSBPFHVGSAVJBDMNPSDKFRXVVPLVAQUGVUJEXSZFGFQIYIJGISUANRAXTGQLAVFMQTICKQAHLEBGHAVOVVPEXIMLFWIYIZIIFSOPCMAWCBPKWZBUQPQLGSNIBFADUUJJHPAIUVVNWNWKDZBHGTEEIISFGIUEUOWXVTPJDVACYQYFQUCXOXOSSMXLZDQESHXKPFEBZHJAGIFGXSMRDKGONGELOALLSYDVILRWAPXXBPOOSWZNEASVJGMAOFLGYIFLJTEKDNIWHJAABCASFMAKIENSYIZZSLRSUIPCJBMQGMPDRCPGWKTPLOTAINXZAAJWCPUJHPOUYWNWHZAKCDMZDSRRRARTVHZYYCEDXJQNQAINQVDJCZCZLCQWQQIKUYMYMOVMNCBVYABTCRRUXVGYLZILFLOFYVWFFBZNFWDZOADRDCLIRFKBFBHMAXX";
char[][] arr = new char[30][50];
int beginCount = 0;
int endCount = 50;
int k = 0;
for(int i = 0; i<30; i++) {
int t = 0;
for(int j = 0; j<50; j++) {
arr[i][j] = str.substring(beginCount,endCount).charAt(t++);
}
beginCount += 50;
endCount += 50;
}
int count = 0;
for(int i = 0; i<30; i++) {
for(int j = 0; j<50; j++) {
for(int l = j; l<50; l++) {
if(arr[i][j]<arr[i][l]) {
count++;
}
}
for(int l = i; l<30; l++) {
if(arr[i][j]<arr[l][j]) {
count++;
}
}
for(int m = i,n=j; m<30&&n<50; m++,n++) {
if(arr[i][j]<arr[m][n]) {
count++;
}
}
//for(int m = i,n=j; m<30&&n<50; m--,n++) {
//注意这里的m>0是约束条件,因为此时我们是斜着右上遍历,m越来越小,当m变为负数是就数组越界,所以限制条件要变一变了
for(int m = i,n=j; m>=0&&n<50; m--,n++) {
if(arr[i][j]<arr[m][n]) {
count++;
}
}
for(int m = i,n=j; m>=0&&n<50; m--,n++) {
if(arr[i][j]>arr[m][n]) {
count++;
}
}
}
}
System.out.println(count);//52800
}
}
这里要注意的点:
-
如何将大段的字符串转化为二位字符数组
-
如何考虑斜着的比较
优化点:
for(int m = i,n=j; m>=0&&n<50; m--,n++) {
if(arr[i][j]<arr[m][n]) {
count++;
}
}
for(int m = i,n=j; m>=0&&n<50; m--,n++) {
if(arr[i][j]>arr[m][n]) {
count++;
}
}
这两部分其实可以写为一个:if(arr[i][j]!=arr[i][j])
就可以啦