一、题目内容

image.png

二、题解

解法1:

思路

代码

  1. public class Solution {
  2. public String solve (String IP) {
  3. // write code here
  4. return validIPv4(IP) ? "IPv4" : (validIPv6(IP) ? "IPv6" : "Neither");
  5. }
  6. private boolean validIPv4(String IP){
  7. String[] strs = IP.split("\\.", -1);
  8. if(strs.length!=4){
  9. return false;
  10. }
  11. for(String str:strs){
  12. if (str.length() > 1 && str.startsWith("0")) {
  13. return false;
  14. }
  15. try {
  16. int val = Integer.parseInt(str);
  17. if (!(val >= 0 && val <= 255)) {
  18. return false;
  19. }
  20. } catch (NumberFormatException numberFormatException) {
  21. return false;
  22. }
  23. }
  24. return true;
  25. }
  26. private boolean validIPv6(String IP) {
  27. String[] strs = IP.split(":", -1);
  28. if (strs.length != 8) {
  29. return false;
  30. }
  31. for (String str : strs) {
  32. if (str.length() > 4 || str.length() == 0) {
  33. return false;
  34. }
  35. try {
  36. int val = Integer.parseInt(str, 16);
  37. } catch (NumberFormatException numberFormatException) {
  38. return false;
  39. }
  40. }
  41. return true;
  42. }
  43. }