1.最长公共前缀
14. 最长公共前缀 - 力扣(LeetCode)
class Solution {
public static String longestCommonPrefix(String[] strs) {
if(strs==null||strs.length==0){
return "";
}
int length=strs.length;
for(int i=0;i<strs[0].length();i++){//第一个字符串的截止范围
char ch=strs[0].charAt(i);//字符串的第一个字母
for(int j=1;j<length;j++){//和每一个字符串是否匹配
if(i==strs[j].length()||strs[j].charAt(i)!=ch){
//弹出的条件
return strs[0].substring(0,i);
}
}
}
return strs[0];
}
}
2.最长回文子串
5. 最长回文子串 - 力扣(LeetCode)
class Solution {
public String longestPalindrome(String s) {
int begin=0,len=0,n=s.length();
for(int i=0;i<n;i++){
//先扩展奇数长度的子串
int left=i,right=i;
while(left>=0&&right<n&&s.charAt(left)==s.charAt(right)){
left--;
right++;
}
if(right-left-1>len){
begin=left+1;
len=right-left-1;
}
//扩展偶数长度的子串
left=i;right=i+1;
while(left>=0&&right<n&&s.charAt(left)==s.charAt(right)){
left--;
right++;
}
if(right-left-1>len){
begin=left+1;
len=right-left-1;
}
}
return s.substring(begin,begin+len);
}
}
3.二进制求和
67. 二进制求和 - 力扣(LeetCode)
class Solution { public String addBinary(String a, String b) { StringBuffer ret=new StringBuffer(); int cur1=a.length()-1,cur2=b.length()-1; int t=0; while(cur1>=0||cur2>=0||t!=0){ if(cur1>=0){ t=t+a.charAt(cur1--)-'0'; } if(cur2>=0){ t=t+b.charAt(cur2--)-'0'; } ret.append((char)('0' + (t % 2))); t=t/2; } ret.reverse(); return ret.toString(); } }
4.字符串相乘
43. 字符串相乘 - 力扣(LeetCode)
class Solution {
public String multiply(String num1, String num2) {
int m = num1.length(), n = num2.length();
char[] n1 = new StringBuffer(num1).reverse().toString().toCharArray();
char[] n2 = new StringBuffer(num2).reverse().toString().toCharArray();
int[] tmp = new int[m + n - 1];
// 1. ⽆进位相乘后相加
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
tmp[i + j] += (n1[i] - '0') * (n2[j] - '0');
// 2. 处理进位
int cur = 0, t = 0;
StringBuffer ret = new StringBuffer();
while (cur < m + n - 1 || t != 0) {
if (cur < m + n - 1)
t += tmp[cur++];
ret.append((char) (t % 10 + '0'));
t /= 10;
}
// 3. 处理进位
while (ret.length() > 1 && ret.charAt(ret.length() - 1) == '0')
ret.deleteCharAt((ret.length() - 1));
return ret.reverse().toString();
}
}