package jz.bm;
import java.util.Arrays;
public class bm8 {
/**
* BM83 字符串变形
*/
public String trans(String s, int n) {
StringBuilder res = new StringBuilder();
//大小写转换
for (int i = 0; i < n; i++) {
if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z') {
res.append(Character.toUpperCase(s.charAt(i)));
} else if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') {
res.append(Character.toLowerCase(s.charAt(i)));
} else {
res.append(s.charAt(i));
}
}
//反转顺序
res = res.reverse();
//单词顺序转换
for (int i = 0; i < n; i++) {
if (res.charAt(i) != ' ') {
int j = i; //每个单词的起点
while (j < n && res.charAt(j) != ' ') {
j++;
}
StringBuilder stringBuilder = new StringBuilder(res.substring(i, j));
res.replace(i, j, stringBuilder.reverse().toString());
i = j;
}
}
return res.toString();
}
/**
* BM84 最长公共前缀
*/
public String longestCommonPrefix (String[] strs) {
if (strs.length == 0) {
return "";
}
StringBuilder res = new StringBuilder();
for (int i = 0; i < strs[0].length(); i++) {
char c = strs[0].charAt(i);
for (int j = 1; j < strs.length; j++) {
if (i >= strs[j].length() || strs[j].charAt(i) != c) {
return res.toString();
}
}
res.append(c);
}
return res.toString();
}
/**
* BM85 验证IP地址
*/
public String solve (String IP) {
if (ipv4(IP)) {
return "IPv4";
} else if (ipv6(IP)) {
return "IPv6";
} else {
return "Neither";
}
}
private boolean ipv4(String IP) {
String[] strings = IP.split("\\.");
//防止尾部是.
if (strings.length != 4 || IP.endsWith(".")) {
return false;
}
for (int i = 0; i < 4; i++) {
if (strings[i].length() == 0) {
return false;
}
for (int j = 0; j < strings[i].length(); j++) {
//开头不能为0
if (j == 0 && strings[i].charAt(j) == '0') {
return false;
}
//10进制
if (strings[i].charAt(j) > '9' || strings[i].charAt(j) < '0') {
return false;
}
}
//0-255
int num = Integer.parseInt(strings[i]);
if (num < 0 || num > 255) {
return false;
}
}
return true;
}
private boolean ipv6(String IP) {
String[] strings = IP.split("\\:");
//防止尾部是:
if (strings.length != 8 || IP.endsWith(":")) {
return false;
}
for (int i = 0; i < 8; i++) {
//不为null,没有多余的0
if (strings[i].length() == 0 || strings[i].length() > 4 || strings[i].startsWith("00")) {
return false;
}
for (int j = 0; j < strings[i].length(); j++) {
//16进制
if (!((strings[i].charAt(j) >= '0' && strings[i].charAt(j) <= '9')
|| (strings[i].charAt(j) >= 'a' && strings[i].charAt(j) <= 'f')
|| (strings[i].charAt(j) >= 'A' && strings[i].charAt(j) <= 'F'))) {
return false;
}
}
}
return true;
}
/**
* BM86 大数加法
*/
public String solve (String s, String t) {
if (s == null || s.equals("")) {
return t;
}
if (t == null || t.equals("")) {
return s;
}
int i = s.length() - 1, j = t.length() - 1;
int carry = 0;
StringBuilder res = new StringBuilder();
while (i >= 0 || j >= 0) {
int a = i < 0 ? 0 : s.charAt(i) - '0';
int b = j < 0 ? 0 : t.charAt(j) - '0';
res.append((a + b + carry) % 10);
carry = (a + b + carry) / 10;
i--;
j--;
}
if (carry != 0) {
res.append(carry);
}
return res.reverse().toString();
}
}
算法练习(8):牛客在线编程08 字符串
最新推荐文章于 2024-10-15 19:28:18 发布