字符串操作算法

  • 回文串
  • 统计字符
  • 翻转单词
  • 替换字符
  • 字符串排序
  • 字符串匹配
1.统计字符串中数字的次数

输入一个字符串(长度在 100 以内),统计其中数字字符出现的次数。

import java.util.Scanner;

public class CountOfNum {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String str = scanner.nextLine();
    scanner.close();
    int num = 0;
    for (int i = 0; i < str.length(); i++) {
      // 转换为字符判断是否有数字
      if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
        num++;
      }
    }
    System.out.print(num);
  }
}
2.替换空格为指定字符串
public String replaceSpace(String str) {
  return str.replaceAll(" ","CODE");
}
public class ReplaceSpaceSolution {

  public static void main(String[] args) {
    System.out.println(replaceSpace(new StringBuffer("Hello Wolrd !lanqiao")));
  }

  public static String replaceSpace(StringBuffer str) {
    // 转换成为字符数组
    char[] originChars = str.toString().toCharArray();
    int spaceNum = 0;
    // 计算出空格的个数
    for (int i = 0; i < originChars.length; i++) {
      if (originChars[i] == ' ') {
        spaceNum++;
      }
    }
    // 新字符数组的长度
    int newCharsLength = originChars.length + 3 * spaceNum;
    char[] newChars = new char[newCharsLength];
    int newStrIndex = 0;
    for (int index = 0; index <= originChars.length - 1; index++) {
      if (originChars[index] != ' ') {
        // 直接复制
        newChars[newStrIndex++] = originChars[index];
      } else {
        // 空格则需要复制几个
        newChars[newStrIndex++] = 'C';
        newChars[newStrIndex++] = 'O';
        newChars[newStrIndex++] = 'D';
        newChars[newStrIndex++] = 'E';
      }
    }
    // 转成字符串
    return new String(newChars);
  }
}
3.翻转句子里的单词
import java.util.ArrayList;
import java.util.List;

public class ReverseString {

    public static void main(String[] args) {
        String str = "I love coding every  day";
        System.out.println(reverseWords(str));
    }

    public static String reverseWords(String s) {
        // 根据空格进行分割
        String[] strs = split(s);
        int size = strs.length;
        // 根据对称轴进行交换
        for (int i = 0; i < size / 2 ; i++) {
            String temp = strs[i];
            strs[i] = strs[size - 1 - i];
            strs[size - 1 - i] = temp;
        }
        // 将子串拼接起来
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < strs.length; i++) {
            // 去掉为空的子串
            if (strs[i].equals("")) {
                continue;
            }
            result.append(strs[i]).append(" ");
        }
        if (result.length() != 0) {
            return result.substring(0, result.length() - 1);
        }
        return "";
    }

    // 实现分割逻辑
    public static String[] split(String s) {
        if (s == null || s.length() == 0) {
            return new String[0];
        }
        List<String> arrayList = new ArrayList<>();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                arrayList.add(stringBuffer.toString());
                stringBuffer = new StringBuffer();
            } else {
                stringBuffer.append(s.charAt(i));
            }
        }

        if (stringBuffer.length() > 0) {
            arrayList.add(stringBuffer.toString());
        }
        return (String[]) arrayList.toArray(new String[0]);
    }
}
4. 寻找最长回文子串
public class LongestPalindrome {

  public static void main(String[] args) {
    LongestPalindrome longestPalindrome = new LongestPalindrome();
    System.out.println(longestPalindrome.longestPalindrome("abdbdc"));
  }

  // 判断是否是回文串
  public boolean isMatch(String s) {
    int len = s.length();
    for (int i = 0; i < len / 2; i++) {
      // 根据中心判断是否相等
      if (s.charAt(i) != s.charAt(len - i - 1)) {
        return false;
      }
    }
    return true;
  }

  public String longestPalindrome(String s) {
    String result = "";
    int max = 0;
    int len = s.length();
    for (int i = 0; i < len; i++)
     for (int j = i + 1; j <= len; j++) {
      // 判断每一段子串
      String str = s.substring(i, j);
      if (isMatch(str) && str.length() > max) {
        result = s.substring(i, j);
        // 记录回文串的最大长度
        max = Math.max(max, result.length());
      }
    }
    return result;
  }
}
5.字符串转整数
public class ConvertNum {
    public static int convert(String str) {
        if (str == null) {
            return 0;
        }
        int i = 0;
        while (i < str.length() && str.charAt(i) == ' ') {
            i++;
        }
        if (i >= str.length()
                || (str.charAt(i) != '-'
                && str.charAt(i) != '+' && !((str.charAt(i) >= '0') && (str.charAt(i) <= '9')))) {
            return 0;
        }
        int sign = 1;
        if (i < str.length() && (str.charAt(i) == '-' || i < str.length() && str.charAt(i) == '+')) {
            sign = str.charAt(i) == '-' ? -1 : 1;
            i++;
        }
        int sum = 0;
        for (; i < str.length(); i++) {
            if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                if (sign == 1) {
                    if (sum > Integer.MAX_VALUE / 10 || sum == Integer.MAX_VALUE / 10 && (str.charAt(i) - '0') > 7) {
                        return Integer.MAX_VALUE;
                    }
                } else {
                    if (sum > (Integer.MAX_VALUE) / 10 || sum == (Integer.MAX_VALUE) / 10 && (str.charAt(i) - '0') > 8) {
                        return Integer.MIN_VALUE;
                    }
                }
                sum = sum * 10 + (str.charAt(i) - '0');
            } else {
                return sum * sign;
            }
        }
        return sum * sign;
    }

    public static void main(String[] args) {
        System.out.println(convert(" 32"));
        System.out.println(convert("+32"));
        System.out.println(convert(" -32"));
        System.out.println(convert("32 abc"));
        System.out.println(convert("8917239179619698"));
    }
}
6.拼接字符串找出最大数
import java.util.Arrays;

public class MinNumberTest {

  public static void main(String args[]) {
    String result = minNumber(new int[] { 3, 32, 321 });
    System.out.print(result);
  }

  public static String minNumber(int[] numbers) {
    String[] strs = new String[numbers.length];
    for (int i = 0; i < numbers.length; i++) strs[i] =
      String.valueOf(numbers[i]);
    Arrays.sort(strs, (x, y) -> (x + y).compareTo(y + x));
    StringBuilder res = new StringBuilder();
    for (String s : strs) res.append(s);
    return res.toString();
  }
}
7.旋转词之 KMP 算法

KMP
1.先得到字串的部分匹配表
2.使用部分匹配表完成KMP匹配

public class KMPSearch {
    public static void main(String[] args) {
        String str1="ABCDABBBCDCD";
        String str2="CDABB";
        int[] next = getNext(str2);
        boolean b = exitSubstring(str1, str2, next);
        System.out.println(b);
    }
    public static int[]  getNext(String str){
        int i=1;int j=0;//i 为后缀末尾;j为前缀的末尾
        int[] next=new int[str.length()];
        for(;i<str.length();i++){
            if(str.charAt(i)==str.charAt(j)){
                j++;
            }else {
                while(j>0&&str.charAt(i)==str.charAt(j)){
                    j=next[j-1];
                }
            }
            next[i]=j;
        }
        return next;
    }
    public static boolean exitSubstring(String str1,String str2,int[]next){
        for(int i=0, j=0;i<str1.length();i++){
            if(str1.charAt(i)==str2.charAt(j)){
                j++;
            }else{
                while (j>0&&str1.charAt(i)!=str2.charAt(j)){
                    j=next[j-1];
                }
            }
            if(j==str2.length()){
                return true;
            }
        }
        return false;
    }
}

Rabin-karp 算法

public class RabinKarp {

  public static void main(String[] args) {
    String source = "ABABDABCD";
    String pattern = "ABC";
    System.out.println(isMatch(pattern, source));
  }

  static boolean isMatch(String pattern, String source) {
    // 计算模式串的 hash 值
    long hash = hash(pattern);
    int pLen = pattern.length();
    for (int i = 0; i + pLen <= source.length(); i++) {
      // 计算子串的 hash 值
      long tempHash = hash(source.substring(i, i + pLen));
      if (hash == tempHash) {
        return true;
      }
    }
    return false;
  }

  private static long hash(String str) {
    long hash = 0;
    for (int i = 0; i != str.length(); i++) {
      hash = 31 * hash + str.charAt(i);
    }
    // 防止溢出
    return hash % Long.MAX_VALUE;
  }
}
字符统计

给定一个长度为 n 的字符串 S,还有一个数字 L,统计长度大于等于 L 的出现次数最多的子串(不同的出现可以相交),如果有多个,输出最长的,如果仍然有多个,输出第一次出现最早的。
输入格式

第一行一个数字 L。

第二行是字符串 S。

L 大于 0,且不超过 S 的长度。

输出格式

一行,题目要求的字符串。

package com.ty.test01;

import java.util.HashMap;
import java.util.Scanner;

public class CharacterCount {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int count = scanner.nextInt();
        String str = scanner.next();
        scanner.close();
        HashMap<String, Integer> map = new HashMap<>();
        String maxStr="";
        int max=0;
        for (int i = 0; i < str.length()-count; i++) {
            for (int j = i+count; j <str.length() ; j++) {
                String substring = str.substring(i, j);
                if(map.containsKey(substring)){
                    int value = map.get(substring);
                    if (value>max) {
                        max=value;
                        maxStr=substring;
                    }else if (value==max){
                        if(maxStr.length()<substring.length()){
                            maxStr=substring;
                        }
                    }
                }else{
                    map.put(substring,0);
                }
            }
        }
        System.out.println(maxStr);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值