题解 | #扑克牌大小#
扑克牌大小
https://www.nowcoder.com/practice/d290db02bacc4c40965ac31d16b1c3eb
import java.util.*; public class Main { // 牌面大小顺序,从小到大排列 private static final List<String> RANK_ORDER = Arrays.asList("3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2", "joker", "JOKER"); public static void main(String[] args) { Scanner fzhinput = new Scanner(System.in); String zfc = fzhinput.nextLine(); String[] pai = zfc.split("-"); String[] pai1 = pai[0].split(" "); String[] pai2 = pai[1].split(" "); String result = comparePokerHands(pai1, pai2); System.out.println(result); } public static String comparePokerHands(String[] pai1, String[] pai2) { String type1 = getHandType(pai1); String type2 = getHandType(pai2); // 判断对王的情况 if (type1.equals("joker_pair")) return String.join(" ", pai1); if (type2.equals("joker_pair")) return String.join(" ", pai2); // 判断炸弹的情况 if (type1.equals("bomb") && type2.equals("bomb")) { return compareSingleCard(pai1[0], pai2[0]) > 0 ? String.join(" ", pai1) : String.join(" ", pai2); } else if (type1.equals("bomb")) { return String.join(" ", pai1); } else if (type2.equals("bomb")) { return String.join(" ", pai2); } // 判断相同类型的牌的情况 if (type1.equals(type2) && pai1.length == pai2.length) { return compareSingleCard(pai1[0], pai2[0]) > 0 ? String.join(" ", pai1) : String.join(" ", pai2); } return "ERROR"; } // 判断手牌的类型 private static String getHandType(String[] hand) { if (hand.length == 2 && hand[0].equals("joker") && hand[1].equals("JOKER")) { return "joker_pair"; // 对王 } else if (hand.length == 4 && allEqual(hand)) { return "bomb"; // 炸弹 } else if (hand.length == 1) { return "single"; // 单张 } else if (hand.length == 2 && allEqual(hand)) { return "pair"; // 对子 } else if (hand.length == 3 && allEqual(hand)) { return "trio"; // 三个 } else if (hand.length == 5 && isStraight(hand)) { return "straight"; // 顺子 } return "unknown"; } // 判断是否所有牌相同 private static boolean allEqual(String[] hand) { for (int i = 1; i < hand.length; i++) { if (!hand[i].equals(hand[0])) return false; } return true; } // 判断是否为顺子 private static boolean isStraight(String[] hand) { for (int i = 0; i < hand.length - 1; i++) { if (RANK_ORDER.indexOf(hand[i + 1]) - RANK_ORDER.indexOf(hand[i]) != 1) { return false; } } return true; } // 比较单张牌的大小 private static int compareSingleCard(String card1, String card2) { return Integer.compare(RANK_ORDER.indexOf(card1), RANK_ORDER.indexOf(card2)); } }