2017-01-22 03:06

# Java 小白求编写一道算法题 能运行出结果立即采纳

class Solution {public String solution（int N，String S，String T）; ｝

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 4条回答默认 最新

• 智_永无止境 2017-01-22 03:28
已采纳

class Solution {
/*
*N 表示地图大小
*S 表示船只的大小
*T 表示被命中的位置
* N = 4，S =“1B 2C，2D 4D”和T =“2B 2D 3D 4D 4A”
* */
public static String solution(int N,String S,String T) throws Exception{
int hitShipLostCount = 0;
int hitShipRunCount = 0;
//获取没亮船只
if(S != null && S != ""){
String[] ships = S.split(",");
//遍历船只，获取船只的每个位置
for (String ship : ships) {
//获取船只最小位置
String shipMin = ship.substring(0,ship.indexOf(" "));
int xMin = Integer.valueOf(shipMin.charAt(0) + "");
char yMin = shipMin.charAt(1);

``````            //获取船只最大位置
String shipMax = ship.substring(ship.indexOf(" ") + 1);
int xMax = Integer.valueOf(shipMax.charAt(0) + "");
char yMax = shipMax.charAt(1);
if(xMax <= N){
//定义集合保存船只的位置
List<String> shipPieces = new ArrayList<String>();
for (int i = xMin; i <= xMax; i++) {
for (int j = yMin; j <= yMax; j++) {
String s = (char)j + "";
}
}

//获取被炮弹命中的位置,并去掉重复的
Set<String> shells = new HashSet<String>();
String[] shellsArr = T.split(" ");
for (String shell : shellsArr) {
}

//用于记录船只被击中的碎片数
int count = 0;
for (String shipPiece : shipPieces) {
for (String shell : shells) {
if(shipPiece.equals(shell)){
count ++ ;
}
}
}

//被击中沉没船只的数量
if(count == shipPieces.size()){
hitShipLostCount ++ ;
}

//击中未沉没船只的数量
if(count > 0 && count < shipPieces.size()){
hitShipRunCount ++ ;
}
}else{
throw new Exception("船只还没有完全进入地图");
}
}
}

return hitShipLostCount + "," + hitShipRunCount;
};

public static void main(String[] args) {
try {
String answer = solution(4,"1B 2C,2D 4D","2B 2D 3D 4D 4A");
} catch (Exception e) {
e.printStackTrace();
}

}
``````

}

``````
``````
点赞 评论
• 奔跑的小鱼儿 2017-01-22 03:18

这主要是很麻烦，需要各种字符拆分和计算，除非很闲才会帮你做，我建议还是自己做吧，不懂就问。

点赞 评论
• Kolamu 2017-01-22 03:38
`````` public String solution(int N, String S, String T){
int x = 0; //命中的数量
int d = 0; //击落的数量

String[] boatArray = S.split("\\,");
String[] hitPosArray = T.split("\\ ");
ArrayList<String> hitPosList = new ArrayList<String>();
for(int i=0;i<hitPosArray.length;i++){
}

for(int i = 0; i < boatArray.length; i++){
String[] boatPos = boatArray[i].split("\\ ");
if(boatPos.length != 2){
return "boat " + i + " position error";
}
String leftTop = boatPos[0];
String rightBottom = boatPos[1];

if(leftTop.length() != 2) return "boat " + i + "leftTop error";
if(rightBottom.length() != 2) return "boat " + i + "rightBottom error";

char left = leftTop.charAt(0);
char top = leftTop.charAt(1);
char right = rightBottom.charAt(0);
char bottom = rightBottom.charAt(1);

ArrayList<String> tmp = new ArrayList<String>();
for(int j=left;j<=right;j++){
for(int k=top;k<=bottom;k++){
}
}

int num =0;
for(int j=0;j<tmp.size();j++){
if(!hitPosList.contains(tmp.get(j))){
num++;
}
}

if(num == 0){
d++;
}else{
x++;
}
}

return d+","+x;
}
``````
点赞 评论
• Kolamu 2017-01-22 03:40

到底采纳谁的了呀，晕死了！

点赞 评论