String字符串相关算法

案例一 判断字符串里括号是否成对出现

题目描述:
判断字符串里括号是否成对出现

 
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
 
public class matchJudger
{
    // pair以右括号为key, 左括号为值
    private Map<Character, Character> pair = null;
 
    public matchJudger()
    {
        pair = new HashMap<Character, Character>();
        pair.put(')', '(');
        pair.put('}', '{');
        pair.put(']', '[');
    }
 
    public boolean isMatch(String s)
    {
        Stack<Character> sc = new Stack<Character>();
        for (int i = 0; i < s.length(); i++)
        {
            Character ch = s.charAt(i);
            if (pair.containsValue(ch))// 如果是左括号,放入栈中
            {
                sc.push(ch);
            } else if (pair.containsKey(ch)) // 如果是右括号
            {
                if (sc.empty()) // 栈为空,栈头没有字符与右括号匹配
                {
                    return false;
                }
                // 栈不为空,栈头字符与右括号匹配
                if (sc.peek() == pair.get(ch))
                {
                    sc.pop();
                } else //网上许多列子没有这里的else代码块,导致({}[]]])会被判断为true
                { // 栈不为空,栈头字符不与右括号匹配
                    return false;
                }
            }
 
        }
 
        return sc.empty() ? true : false;
    }
 
    public static void main(String[] args)
    {
        matchJudger judger = new matchJudger();
        System.out.println(judger.isMatch("(***)-[{-------}]")); //true
        System.out.println(judger.isMatch("(2+4)*a[5]")); //true
        System.out.println(judger.isMatch("({}[]]])")); //false
        System.out.println(judger.isMatch("())))")); //false
    }
 
}

案例二 实现字符串反转

题目描述:
实现字符串反转

package num_value.String_Calculate;

/**
 * 手动实现 字符串翻转函数
 *    功能1: 将hello 变为 olleh
 *    功能2: 将hello the world变为 dlrow eht olleh
 *    功能3: 将hello the world 变为 world the hello
 */
public class test2 {
    public static void main(String[] args) {
        String s="hello the world";
        System.out.println(reverseWords(s));
        System.out.println(reverse(reverseWords(s)));
    }


    //实现字符串单个串翻转。=>自己写的
    private static String reverse(String s){
        char[] charArr=s.toCharArray();
        int l=0;
        int r=charArr.length-1;
        while (l<r){
            char temp=charArr[r];
            charArr[r]=charArr[l];
            charArr[l]=temp;
            l++;
            r--;
        }
        return new String(charArr);
    }


    //将每一个单词都翻转后,输出
    public static String reverseWords(String s) {
        if (s.equals("")) {
            return "";
        }
        char[] arr = s.toCharArray();
        int n = arr.length;
        if (n <= 1) {
            return null;
        }
        int l = 0;

        int r = 0;
        int i = 0;
        while (i < n) {
            //找到l的位置
            for (; i < n; i++) {
                if (arr[i] != ' ') {
                    l = i;
                    break;
                }else {
                    i++;
                }
            }
            //找到r的位置
            while (i < n) {
                if (i == n-1) {
                    r = n - 1;
                    reverseString(arr,l,r);
                    i++;
                    break;
                }
                if (arr[i] == ' ') {
                    r = i - 1;
                    reverseString(arr,l,r);
                    i++;
                    break;
                }else {
                    i++;
                }
            }
        }
        return new String(arr);
    }

    // 参考网上代码
    public static void reverseString(char[] s, int l, int r) {
        int n = s.length;
        if (n <= 1) {
            return;
        }
        while (l < r) {
            char temp = s[l];
            s[l] = s[r];
            s[r] = temp;
            l++;
            r--;
        }
    }
}

案例三 父字符串parent 子字符串child

题目描述
需求:父字符串parent 子字符串child
求child 是否是parent的字串,如果是返回匹配初始索引

package num_value.String_Calculate;

/**
 * 需求:父字符串parent 子字符串child
 * 求child 是否是parent的字串,如果是返回匹配初始所以
 */


public class test3 {

    public static void main(String[] args) {

        //返回子串sub在s中第一次出现的位置,如果没找到返回-1
        String s = "aasaewqewqeqw";
        String sub = "ewq";
        System.out.println(IndexOf(s, sub));

    }

    public static int IndexOf(String s, String sub) {
        char[] sChars = s.toCharArray();
        char[] subChars = sub.toCharArray();
        int sLength = s.length();
        int subLength = sub.length();

        int sIndex = 0;
        int subIndex = 0;
        while (sIndex < sLength && subIndex < subLength) {
            if (sChars[sIndex] == subChars[subIndex]) {
                subIndex++;
                sIndex++;
            } else {
                sIndex = sIndex + 1;
                subIndex = 0;
            }
        }

        int index = subIndex == subLength ? (subLength > 1 ? sIndex - subLength : sIndex - 1) : -1;
        return index;
    }

}


案例 四:求两个字符串的最长公共连续串

public class Main03{
    // 求解两个字符号的最长公共子串
    public static String maxSubstring(String strOne, String strTwo){
        // 参数检查
        if(strOne==null || strTwo == null){
            return null;
        }
        if(strOne.equals("") || strTwo.equals("")){
            return null;
        }
        // 二者中较长的字符串
        String max = "";
        // 二者中较短的字符串
        String min = "";
        if(strOne.length() < strTwo.length()){
            max = strTwo;
            min = strOne;
        } else{
            max = strTwo;
            min = strOne;
        }
        String current = "";
        // 遍历较短的字符串,并依次减少短字符串的字符数量,判断长字符是否包含该子串
        for(int i=0; i<min.length(); i++){
            for(int begin=0, end=min.length()-i; end<=min.length(); begin++, end++){
                current = min.substring(begin, end);
                if(max.contains(current)){
                    return current;
                }
            }
        }
        return null;
    }
     
    public static void main(String[] args) {
        String strOne = "abcdefg";
        String strTwo = "adefgwgeweg";
        String result = Main03.maxSubstring(strOne, strTwo);
        System.out.println(result);
    }
}

案例五 求字符串数组中最长前缀

  if (strs.length == 0) return "";
   String prefix = strs[0];
   for (int i = 1; i < strs.length; i++)
       while (strs[i].indexOf(prefix) != 0) {
           prefix = prefix.substring(0, prefix.length() - 1);
           if (prefix.isEmpty()) return "";
       }        
   return prefix;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值