/**
* 14、最长公共前缀
*
* @param strs
* @return
*/
public static String longestCommonPrefix(String[] strs) {
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
// 先找出一个数组内最小字符串下标
int minStrIndex = 0;
for (int i = 0; i < strs.length; i++) {
if (strs[i].length() < strs[minStrIndex].length()) {
minStrIndex = i;
}
}
String compareString = strs[minStrIndex];
for (String str : strs) {
while (!str.startsWith(compareString)) {
// 不匹配减一重新匹配
compareString = compareString.substring(0, compareString.length() - 1);
}
}
return compareString;
}
/**
* 9、回文数
*
* @param x
* @return
*/
public static boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
char[] xChars = String.valueOf(x).toCharArray();
for (int i = 0; i < (xChars.length / 2); i++) {
if (xChars[i] != xChars[xChars.length - 1 - i]) {
return false;
}
}
return true;
}
/**
* 7、整数反转
*
* @param x
* @return
*/
public static int reverse(int x) {
String xString = String.valueOf(x);
if (xString.length() == 0) {
return 0;
}
if (xString.length() == 1) {
return x;
}
try {
if ("-".equals(xString.substring(0, 1))) {
//负数
String sign = xString.substring(0, 1);
String other = xString.substring(1);
char[] otherChars = other.toCharArray();
StringBuilder newOther = new StringBuilder();
for (int i = otherChars.length - 1; i >= 0; i--) {
newOther.append(otherChars[i]);
}
return Integer.parseInt(sign + newOther.toString());
} else {
//整数
char[] otherChars = xString.toCharArray();
StringBuilder newOther = new StringBuilder();
for (int i = otherChars.length - 1; i >= 0; i--) {
newOther.append(otherChars[i]);
}
return Integer.parseInt(newOther.toString());
}
} catch (Exception e) {
return 0;
}
}