字符串常考面试题
大数相加
import java.util.*;
public class Solution {
public String solve (String s, String t) {
// write code here
if(s == null || "".equals(s)) {
return t;
}
if(t == null || "".equals(t)) {
return s;
}
int i = s.length() - 1;
int j = t.length() - 1;
int carry = 0;
StringBuffer ret = new StringBuffer();
while(i >= 0 || j >= 0) {
int n1 = i >= 0 ? s.charAt(i) - '0' : 0;
int n2 = j >= 0 ? t.charAt(j) - '0' : 0;
int sum = n1 + n2 + carry;
ret.append((char)((sum % 10) + '0'));
carry = sum / 10;
i--;
j--;
}
if(carry > 0) {
ret.append('1');
}
ret.reverse();
return ret.toString();
}
}
大数相乘
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param s string字符串 第一个整数
* @param t string字符串 第二个整数
* @return string字符串
*/
public String solve (String s, String t) {
// write code here
if(s == null || "".equals(s)) {
return t;
}
if(t == null || "".equals(t)) {
return s;
}
int len1 = s.length() - 1;
int len2 = t.length() - 1;
int[] mul = new int[len1 + len2 + 2];
for(int i = len1; i >= 0; i--) {
for(int j = len2; j >= 0; j--) {
int sum = (s.charAt(i)-'0') * (t.charAt(j)-'0');
sum += mul[i + j + 1]; // 先加低位判断是否有新的进位
mul[i + j] += sum / 10;
mul[i + j + 1] = sum % 10;
}
}
StringBuilder ret = new StringBuilder();
int i = 0;
// 去掉前导0
while(i < mul.length-1 && mul[i] == 0) {
i++;
}
for(; i < mul.length; ++i) {
ret.append(mul[i]);
}
return ret.toString();
}
}
两数相加
https://leetcode-cn.com/problems/add-two-numbers/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null) {
return l2;
}
if(l2 == null) {
return l1;
}
ListNode head = null;
ListNode tail = null;
int carry = 0;
while(l1 != null || l2 != null) {
int n1 = l1 != null ? l1.val : 0;
int n2 = l2 != null ? l2.val : 0;
int sum = n1 + n2 + carry;
if(head == null) {
head = tail = new ListNode(sum % 10);
}else {
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
carry = sum / 10;
if(l1 != null) {
l1 = l1.next;
}
if(l2 != null) {
l2 = l2.next;
}
}
if(carry > 0) {
tail.next = new ListNode(carry);
}
return head;
}
}
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null) {
return l2;
}
if(l2 == null) {
return l1;
}
ListNode newHead = new ListNode(-1);
ListNode tmp = newHead;
int carry = 0;
while(l1 != null || l2 != null) {
int n1 = l1 != null ? l1.val : 0;
int n2 = l2 != null ? l2.val : 0;
int sum = n1 + n2 + carry;
carry = sum / 10;
ListNode node = new ListNode(sum % 10);
tmp.next = node;
tmp = node;
if(l1 != null) {
l1 = l1.next;
}
if(l2 != null) {
l2 = l2.next;
}
}
if(carry > 0) {
tmp.next = new ListNode(1);
}
return newHead.next;
}
}
链表相加
import java.util.*;
public class Solution {
public ListNode reverse(ListNode head) {
if(head == null) {
return null;
}
ListNode cur = head;
ListNode prev = null;
ListNode curNext = null;
while(cur != null) {
curNext = cur.next;https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b?tpId=117&&tqId=37814&&companyId=665&rp=1&ru=/company/home/code/665&qru=/ta/job-code-high/question-ranking
cur.next = prev;
prev = cur;
cur = curNext;
}
return prev;
}
public ListNode addInList (ListNode h1, ListNode h2) {
// write code here
if(h1 == null) {
return h2;
}
if(h2 == null) {
return h1;
}
ListNode newH1 = reverse(h1);
ListNode newH2 = reverse(h2);
ListNode head = null, tail = null;
int carry = 0;
while(newH1 != null || newH2 != null) {
int n1 = newH1 != null ? newH1.val : 0;
int n2 = newH2 != null ? newH2.val : 0;
int sum = n1 + n2 + carry;
if(head == null) {
head = tail = new ListNode(sum % 10);
}else {
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
carry = sum / 10;
if(newH1 != null) {
newH1 = newH1.next;
}
if(newH2 != null) {
newH2 = newH2.next;
}
}
if(carry > 0) {
tail.next = new ListNode(carry);
}
ListNode ret = reverse(head);
return ret;
}
}
二进制求和
https://leetcode-cn.com/problems/add-binary/
class Solution {
public String addBinary(String s1, String s2) {
if(s1 == null || s1.length() == 0) {
return s2;
}
if(s2 == null || s2.length() == 0) {
return s1;
}
StringBuffer ret = new StringBuffer();
int carry = 0;
int i = s1.length() - 1;
int j = s2.length() - 1;
while(i >= 0 || j >= 0) {
int n1 = i >= 0 ? s1.charAt(i) - '0' : 0;
int n2 = j >= 0 ? s2.charAt(j) - '0' : 0;
int sum = n1 + n2 + carry;
ret.append(sum % 2);
carry = sum / 2;
i--;
j--;
}
if(carry > 0) {
ret.append('1');
}
return ret.reverse().toString();
}
}
数组中相加和为0的三元组
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(int[] nums) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
if(nums == null || nums.length == 0) {
return ret;
}
int len = nums.length;
Arrays.sort(nums);
for(int i = 0; i < len; i++) {
if(nums[i] > 0) {
break;
}
if(i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int l = i + 1, r = len - 1;
while(l < r) {
int sum = nums[i] + nums[l] + nums[r];
if(sum == 0) {
ArrayList<Integer> tmp = new ArrayList<>();
tmp.add(nums[i]);
tmp.add(nums[l]);
tmp.add(nums[r]);
ret.add(tmp);
while(l < r && nums[l] == nums[l + 1]) {
l++;
}
l++;
}else if(sum < 0) {
l++;
}else {
r--;
}
}
}
return ret;
}
}
把字符串转成整数
https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/
class Solution {
public int strToInt(String str) {
//先去空格再判空,不然" "教您做人,血的教训
str = str.trim();
if(str.length() == 0){
return 0;
}
//然后我想啊,下面要判断首位了
//首位合格的无非就'+'或'-'或数字三种情况,其他的一概滚蛋
//'+''-'肯定是要把它去掉的,这样三种情况就统一了
//当然了,'-abc'这种有可能出现,不过只看首位它是没毛病的
//让它进来,反正后面很容易解决
//既然要去掉正负号,那肯定要出个boolean记一下是不是负数
boolean isMinus = false;
char[] ch = str.toCharArray();
//首位是不是正负号或者数字啊
if(ch[0] == '+' || ch[0] == '-' || Character.isDigit(ch[0])){
//是不是正负号啊
if(ch[0] == '+' || ch[0] == '-'){
//是不是负号啊
if(ch[0] == '-'){
isMinus = true;
}
//删除首位
ch = Arrays.copyOfRange(ch,1,ch.length);
}
//首位搞定了就看后面是不是数字了,直到不是数字的地方或者倒底结束
int index = 0;
//结果可能超int范围,拿个long接一下
//'-abc'这种情况返回的也是0,舒服,一箭双雕
long res = 0;
//短路与助您远离空指针喔,铁汁们,先后顺序关注一下
while(index < ch.length && Character.isDigit(ch[index])){
//一位一位往上算
res *= 10;
res += ch[index] - '0';
//及时止损,一看到res超int范围立马return
//你要是想着最后一起算,那肯定会有超long范围的测试用例等着你,你就哭去吧
if(res > Integer.MAX_VALUE){
//正负号看是正数负数,返回最大值
return isMinus ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
//别忘了往后走一位
index++;
}
//long转int就是这么朴实无华
return isMinus ? -(int)res : (int)res;
}
//兄弟首位都不对想啥呢,回去吧您
return 0;
}
}
第一个只出现一次的字符
https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/
public char firstUniqChar(String s) {
if(s == null || s.length() == 0) return ' ';
HashMap<Character, Integer> map = new HashMap<>();
for(int i = 0;i < s.length();i++){
char c = s.charAt(i);
if(map.containsKey(c)){
map.put(c, map.get(c) + 1);
}
else
map.put(c, 1);
}
for(int i = 0;i < s.length();i++){
if(map.get(s.charAt(i)) == 1){
return s.charAt(i);
}
}
return ' ';
}
最长公共前缀
https://leetcode-cn.com/problems/longest-common-prefix/
class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs == null || strs.length == 0) {
return "";
}
String ret = strs[0];
for(int i = 0; i < strs[0].length(); i++) {
for(int j = 1; j < strs.length; j++) {
if(i == strs[j].length() || strs[0].charAt(i) != strs[j].charAt(i)) {
return ret.substring(0, i);
}
}
}
return ret;
}
}
反转字符串
class Solution {
public void reverseString(char[] s) {
if(s == null || s.length == 0) {
return ;
}
int i = 0, j = s.length - 1;
while(i < j) {
char tmp = s[i];
s[i] = s[j];
s[j] = tmp;
i++;
j--;
}
return ;
}
}
反转字符串II(反转k个)
https://leetcode-cn.com/problems/reverse-string-ii/
class Solution {
public String reverseStr(String s, int k) {
char[] a = s.toCharArray();
for (int start = 0; start < a.length; start += 2 * k) {
int i = start, j = Math.min(start + k - 1, a.length - 1);
while (i < j) {
char tmp = a[i];
a[i++] = a[j];
a[j--] = tmp;
}
}
return new String(a);
}
}
仅仅反转字母
https://leetcode-cn.com/problems/reverse-only-letters/
class Solution {
public String reverseOnlyLetters(String S) {
StringBuilder ret = new StringBuilder();
int j = S.length() - 1;
for (int i = 0; i < S.length(); ++i) {
if (Character.isLetter(S.charAt(i))) {
while (!Character.isLetter(S.charAt(j)))
j--;
ret.append(S.charAt(j--));
} else {
ret.append(S.charAt(i));
}
}
return ret.toString();
}
}
反转单词(顺序改变)
https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/
class Solution {
public String reverseWords(String s) {
int j = s.length() - 1, i = j;
StringBuffer ret = new StringBuffer();
while(i >= 0) {
while(i >= 0 && s.charAt(i) != ' ') {
i--;
}
ret.append(s.substring(i + 1, j + 1) + " ");
while(i >= 0 && s.charAt(i) == ' ') {
i--;
}
j = i;
}
return ret.toString().trim();
}
}
反转单词(顺序不变)
https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/
class Solution {
public String reverseWords(String s) {
String[] strs = s.split(" ");
StringBuffer ret = new StringBuffer();
for (int i = 0; i < strs.length; i++) {
ret.append(new StringBuffer(strs[i]).reverse().toString());
ret.append(" ");
}
return ret.toString().trim();
}
}
有效括号序列(括号匹配)
import java.util.*;
public class Solution {
public boolean isValid (String s) {
if(s == null || s.length() == 0) {
return false;
}
Stack<Character> stk = new Stack<>();
for(int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if((ch == '(') || (ch == '[') || (ch == '{')) {
stk.push(ch);
}else if((ch == ')') || (ch == ']') || (ch == '}')){
if(stk.isEmpty()) {
return false;
}else {
char top = stk.peek();
if((top == '(' && ch == ')') || (top == '[' && ch == ']') || (top == '{' && ch == '}')) {
stk.pop();
}else {
return false;
}
}
}
}
if(stk.isEmpty()) {
return true;
}
return false;
}
}
大数加法
import java.util.*;
public class Solution {
public String solve (String s, String t) {
// write code here
if(s == null || "".equals(s)) {
return t;
}
if(t == null || "".equals(t)) {
return s;
}
int i = s.length() - 1;
int j = t.length() - 1;
StringBuffer ret = new StringBuffer();
int carry = 0;
while(i >= 0 || j >= 0) {
int n1 = i >= 0 ? s.charAt(i) - '0' : 0;
int n2 = j >= 0 ? t.charAt(j) - '0' : 0;
int sum = n1 + n2 + carry;
carry = sum / 10;
ret.append(sum % 10);
i--;
j--;
}
if(carry > 0) {
ret.append('1');
}
return ret.reverse().toString();
}
}
字符串的排列
牛客
import java.util.ArrayList;
import java.util.*;
public class Solution {
public ArrayList<String> ret = new ArrayList<>();
public ArrayList<String> Permutation(String s) {
if(s.length() == 0) {
return ret;
}
int n = s.length();
char[] str = s.toCharArray();
Arrays.sort(str);
StringBuffer path = new StringBuffer();
boolean[] used = new boolean[n];
dfs(str, n, 0, used, ret, path);
return ret;
}
public void dfs(char[] str, int len, int depth, boolean[] used, List<String> ret, StringBuffer path ) {
if(depth == len) {
ret.add(path.toString());
}
for(int i = 0; i < len; i++) {
if(used[i]) {
continue;
}
if(i > 0 && str[i] == str[i - 1] && !used[i - 1]) {
continue;
}
path.append(str[i]);
used[i] = true;
dfs(str, len, depth + 1, used, ret, path);
used[i] = false;
path.deleteCharAt(path.length() - 1);
}
}
}
力扣
class Solution {
public List<String> ret = new ArrayList<>();
public String[] permutation(String s) {
if(s.length() == 0) {
return new String[0];
}
int n = s.length();
char[] str = s.toCharArray();
Arrays.sort(str);
StringBuffer path = new StringBuffer();
boolean[] used = new boolean[n];
dfs(str, n, 0, used, ret, path);
return ret.toArray(new String[0]);
}
public void dfs(char[] str, int len, int depth, boolean[] used, List<String> ret, StringBuffer path ) {
if(depth == len) {
ret.add(path.toString());
}
for(int i = 0; i < len; i++) {
if(used[i]) {
continue;
}
if(i > 0 && str[i] == str[i - 1] && !used[i - 1]) {
continue;
}
path.append(str[i]);
used[i] = true;
dfs(str, len, depth + 1, used, ret, path);
used[i] = false;
path.deleteCharAt(path.length() - 1);
}
}
}
最长回文子串
import java.util.*;
public class Solution {
public static boolean isHuiWen(String s) {
if(s == null ||s.length() == 0) {
return false;
}
int i = 0, j = s.length() - 1;
while(i < j) {
if(s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
public int getLongestPalindrome (String s) {
int n = s.length();
int ret = 0;
for(int i = 0; i < n; i++) {
for(int j = i + 1; j <= n; j++) {
if(isHuiWen(s.substring(i, j))) {
if(ret < j - i) {
ret = j - i;
}
}
}
}
return ret;
}
}
最长公共前缀
import java.util.*;
public class Solution {
public String longestCommonPrefix (String[] strs) {
// write code here
if(strs == null || strs.length == 0) {
return "";
}
String ret = strs[0];
for(int i = 0; i < strs[0].length(); i++) {
for(int j = 1; j < strs.length; j++) {
if(i == strs[j].length() || strs[0].charAt(i) != strs[j].charAt(i)) {
return ret.substring(0, i);
}
}
}
return ret;
}
}
判断字符串是否回文
import java.util.*;
public class Solution {
public boolean judge (String s) {
// write code here
if(s == null ||s.length() == 0) {
return false;
}
int i = 0, j = s.length() - 1;
while(i < j) {
if(s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}
字符串变形
import java.util.*;
public class Solution {
// 反转字符串大小写
public String func(String str){
StringBuilder ret = new StringBuilder();
for(int i = 0; i < str.length(); i++){
if(Character.isUpperCase(str.charAt(i))){
ret.append(Character.toLowerCase(str.charAt(i)));
}else{
ret.append(Character.toUpperCase(str.charAt(i)));
}
}
return ret.toString();
}
public String trans(String s, int n) {
String[] strs = s.split(" ", -1);// 这里,limit设置为-1,模式可以应用无数次
StringBuilder ret = new StringBuilder();
for(int i = strs.length - 1; i >= 0; i--){
ret.append(func(strs[i]));
if(i != 0){
ret.append(" ");
}
}
return ret.toString();
}
}
数字字符串转换成ip地址
import java.util.*;
public class Solution {
/**
*
* @param s string字符串
* @return string字符串ArrayList
*/
ArrayList<String> ret = new ArrayList<>();
ArrayList<String> path = new ArrayList<>();
public ArrayList<String> restoreIpAddresses (String s) {
// write code here
if(s.length() > 12 || s.length() < 4){
return ret;
}
dfs(s, 0, ret, path);
return ret;
}
private void dfs(String s, int depth, List<String> ret, List<String> path){
int n = s.length();
int size = path.size();
if(3 * (4 - size) < n - depth || n - depth < (4 - size)){
// 剩下的分不完了,剪枝
return;
}
if(size == 4 && depth == n){
// 正确的情况
StringBuilder tmp = new StringBuilder();
boolean first = true;
for(String str : path){
if(!first){
tmp.append(".");
}
first = false;
tmp.append(str);
}
ret.add(tmp.toString());
return;
}
// 如果是0需要特判
if(s.charAt(depth) == '0'){
path.add("0");
dfs(s, depth + 1, ret, path);
path.remove(path.size() - 1);
}else{
// 防止越界
int right = Math.min(depth + 3, n);
for(int i = depth; i < right; i++){
String tmp = s.substring(depth, i + 1);
if(check(tmp)){
path.add(tmp);
dfs(s, i + 1, ret, path);
path.remove(path.size() - 1);
}
}
}
}
private boolean check(String s){
int num = Integer.valueOf(s);
return num <= 255 && num >= 0;
}
}
验证一个字符串是不是ipv4
public static boolean func(String str) {
if(str == null || str.length() == 0) {
return false;
}
String[] strs = str.split("\\.");
if(strs.length != 4) {
return false;
}
for(String s : strs) {
if(s.length() == 0 || s.length() > 3) {
return false;
}
for(int i = 0; i < s.length(); i++) {
if(!Character.isDigit(s.charAt(i))) {
return false;
}
}
int num = Integer.valueOf(s);
if(num < 0 || num > 255) {
return false;
}
if(String.valueOf(num).length() < s.length()) {
return false;
}
}
return true;
}
验证ip地址
import java.util.*;
public class Solution {
public String solve (String IP) {
String ip = IP.toLowerCase();
//-1的作用,保存空值
String[] ipv4 = ip.split("\\.",-1);
//判断它的长度
if(ipv4.length == 4){
return checkIPV4(ipv4);
}
String[] ipv6 = ip.split(":",-1);
if(ipv6.length == 8){
return checkIPV6(ipv6);
}
return "Neither";
}
public String checkIPV4(String[] ip){
for(String s:ip){
int n = s.length();
//判断长度
if(n == 0|| n > 3){
return "Neither";
}
for(int i = 0;i < n; i++){
if(!Character.isDigit(s.charAt(i))){
return "Neither";
}
}
//检查范围,这个的地方可以把前面有0的转化成前面没0
int num = Integer.valueOf(s);
if(num < 0 || num > 255){
return "Neither";
}
//检查第一位有没有0
if(String.valueOf(num).length() < n){
return "Neither";
}
}
return "IPv4";
}
public String checkIPV6(String[] ip){
for(String s:ip){
int n = s.length();
//判断每位的长度,没有或者大于4位不满足
if(n == 0|| n > 4){
return "Neither";
}
for(int i = 0; i < n; i++){
char c = s.charAt(i);
//判断16进制
if((c >= '0' && c <= '9') || (c >= 'a'&& c <= 'f')){
continue;
}
return "Neither";
}
}
return "IPv6";
}
}
把字符串转换为整数
import java.util.*;
public class Solution {
public int StrToInt (String str) {
// write code here
//先去空格再判空,不然" "教您做人,血的教训
str = str.trim();
if(str.length() == 0){
return 0;
}
//然后我想啊,下面要判断首位了
//首位合格的无非就'+'或'-'或数字三种情况,其他的一概滚蛋
//'+''-'肯定是要把它去掉的,这样三种情况就统一了
//当然了,'-abc'这种有可能出现,不过只看首位它是没毛病的
//让它进来,反正后面很容易解决
//既然要去掉正负号,那肯定要出个boolean记一下是不是负数
boolean isMinus = false;
char[] ch = str.toCharArray();
//首位是不是正负号或者数字啊
if(ch[0] == '+' || ch[0] == '-' || Character.isDigit(ch[0])){
//是不是正负号啊
if(ch[0] == '+' || ch[0] == '-'){
//是不是负号啊
if(ch[0] == '-'){
isMinus = true;
}
//删除首位
ch = Arrays.copyOfRange(ch,1,ch.length);
}
//首位搞定了就看后面是不是数字了,直到不是数字的地方或者倒底结束
int index = 0;
//结果可能超int范围,拿个long接一下
//'-abc'这种情况返回的也是0,舒服,一箭双雕
long res = 0;
//短路与助您远离空指针喔,铁汁们,先后顺序关注一下
while(index < ch.length && Character.isDigit(ch[index])){
//一位一位往上算
res *= 10;
res += ch[index] - '0';
//及时止损,一看到res超int范围立马return
//你要是想着最后一起算,那肯定会有超long范围的测试用例等着你,你就哭去吧
if(res > Integer.MAX_VALUE){
//正负号看是正数负数,返回最大值
return isMinus ? Integer.MIN_VALUE : Integer.MAX_VALUE;
}
//别忘了往后走一位
index++;
}
//long转int就是这么朴实无华
return isMinus ? -(int)res : (int)res;
}
//兄弟首位都不对想啥呢,回去吧您
return 0;
}
}
编辑距离(二)
import java.util.*;
public class Solution {
public int min(int a,int b){
return a<b ? a:b;
}
public int minEditCost (String str1, String str2, int ic, int dc, int rc) {
// write code here
int[][] dp = new int[str1.length()+1][str2.length()+1];
//str1为空 ,变成str2 是插入操作
for(int i=0;i<dp[0].length;i++){
dp[0][i]=i*ic;
}
//str1非空 str2为空 是删除操作
for(int j=0;j<dp.length;j++){
dp[j][0]=j*dc;
}
for(int i=1;i<dp.length;i++){
for(int j=1;j<dp[0].length;j++){
if(str1.charAt(i-1)==str2.charAt(j-1)){//当前元素匹配
dp[i][j]=dp[i-1][j-1];
}else{//当前元素不匹配
//dp[i-1][j-1]+rc 在str1[0,i-1] 与str2[0,j-1]匹配的情况下需要替换,说明str1[i]需要
//dp[i-1][j]+dc str1[0,i-1] 与str2[0,j]匹配的情况下需要删除,说明str1[i]多余了
//dp[i][j-1]+ic str1[0,i] 与str2[0,j-1]匹配的情况下需要增加,说明str[i]之后还得补一个元素。
dp[i][j]=min(dp[i-1][j-1]+rc,min(dp[i-1][j]+dc,dp[i][j-1]+ic ));
}
}
}
return dp[str1.length()][str2.length()];
}
}
最长括号子串
import java.util.*;
public class Solution {
public int longestValidParentheses (String s) {
// write code here
if (s == null || s.length() < 2) {
return 0;
}
int[] f = new int[s.length()];
if (s.charAt(0) == '(' && s.charAt(1) == ')') {
f[1] = 2;
}
int ret = Math.max(f[1], 0);
for (int i = 2; i < s.length(); i++) {
if (s.charAt(i) == ')') {
if (s.charAt(i - 1) == '(') {
f[i] = 2 + f[i - 2];
} else {
int index = i - f[i - 1] - 1;
if (index >= 0 && s.charAt(index) == '(') {
f[i] = 2 + f[i - 1];
if (index - 1 >= 0) {
f[i] += f[index - 1];
}
}
}
}
ret = Math.max(ret, f[i]);
}
return ret;
}
}
表达式求值
import java.util.*;
public class Solution {
public int solve (String s) {
// write code here
if(s == null) return 0;
Stack<Integer> numStack= new Stack<>();
Stack<Character> opStack= new Stack<>();
for(int i=0;i<s.length();i++){
//处理数字栈
if(s.charAt(i)>='0'&&s.charAt(i)<='9'){
if(i==0){
numStack.add(s.charAt(i)-'0');
}else{
if(s.charAt(i-1)>='0'&&s.charAt(i)<='9'){
int tmp=numStack.pop();
int num=tmp*10+(s.charAt(i)-'0');
numStack.add(num);
}else{
numStack.add(s.charAt(i)-'0');
}
}
}else{
//处理符号栈
if(opStack.isEmpty()){
opStack.add(s.charAt(i));
}else{
if(s.charAt(i) == '('){
opStack.push(s.charAt(i));
}else if(s.charAt(i) == ')'){
while(opStack.peek() != '('){
cal(numStack, opStack.pop());
}
opStack.pop();
}else if(s.charAt(i) == '*'){
if(opStack.peek() == '*'){
cal(numStack, opStack.pop());
}
opStack.push(s.charAt(i));
}else if(s.charAt(i) == '+' || s.charAt(i) == '-'){
if(opStack.peek() != '('){
cal(numStack, opStack.pop());
}
opStack.push(s.charAt(i));
}
}
}
}
while(!opStack.isEmpty()){
cal(numStack,opStack.pop());
}
return numStack.pop();
}
public void cal(Stack<Integer> stackInt, char ope){
int x = stackInt.pop();
int y = stackInt.pop();
if(ope == '*'){
stackInt.push(x * y);
}else if(ope == '+'){
stackInt.push(x + y);
}else if(ope == '-'){
stackInt.push(y - x);
}
}
}
字符串中的topk问题
- 如果value不为空,进行merge处理。为空直接赋值newValue。实际上就是一个put操作。然后将key对应的oldValue和newValue 根据传来的function进行处理。
- 2 当处理后的value值为空,map会移除当前key
import java.util.*;
public class Solution {
public String[][] topKstrings (String[] strings, int k) {
// write code here
HashMap<String, Integer> map = new HashMap<>();
for (String string : strings) {
map.merge(string, 1, Integer::sum);
}
Set<String> set = map.keySet();
List<String> str = new ArrayList<>(set);
str.sort((s1, s2) -> map.get(s1).equals(map.get(s2)) ? s1.compareTo(s2) : map.get(s2) - map.get(s1));
String[][] ret = new String[k][2];
for (int i = 0; i < k; i++) {
ret[i] = new String[]{str.get(i), String.valueOf(map.get(str.get(i)))};
}
return ret;
}
}
删除驼峰字符串
给定一个驼峰样式的字符串例如“AaABbBcBbcvQv…”->“bc”,两个一样的字符夹着一个不一样的字符, 处理这个字符串去掉所有的驼峰。
public static String func(String s){
StringBuilder ret = new StringBuilder();
char pre;
LinkedList<Character> list = new LinkedList<>();
list.add(s.charAt(0));
list.add(s.charAt(1));
int k = 2;
for(int i = 2; i < s.length(); i++){
pre = s.charAt(i - 2);
if(s.charAt(i) != pre){
list.add(s.charAt(i));
k++;
}else{
if(k > 2){
k = 2;
}
while(k > 0){
list.remove(list.size() - 1);
k--;
}
}
}
for(int i = 0;i < list.size(); i++){
ret.append(list.get(i));
}
return ret.toString();
}
public static void main(String args[]){
String s = "AaABbBcBbcvQvaaaaaaaaaaaaaa";
System.out.print(func(s));
}
字符串压缩
https://leetcode-cn.com/problems/compress-string-lcci/
class Solution {
public String compressString(String S) {
if(S == null) {
return "";
}
int i = 0;
int j = 0;
int n = S.length();
StringBuilder ret = new StringBuilder();
while (i < n) {
while (j < n && S.charAt(i) == S.charAt(j)) {
j++;
}
ret.append(S.charAt(i));
if((j - i) == 1) {
ret.append(1);
}else{
ret.append(j - i);
}
i = j;
}
String ans = ret.toString();
if(ans.length() >= S.length()) {
return S;
}else {
return ans;
}
}
}
字符的大小写转换
public static boolean isUpper(char ch) {
if(ch >= 'A' && ch <= 'Z') {
return true;
}else {
return false;
}
}
public static boolean isLower(char ch) {
if(ch >= 'a' && ch <= 'z') {
return true;
}else {
return false;
}
}
public static char toUpper(char ch) {
return (char) (ch - 32);
}
public static char toLower(char ch) {
return (char) (ch + 32);
}