leetcode字符串相关题目

字符串相关题

剑指 Offer 58 - II

https://leetcode.cn/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/

题目:

字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。

思路:

要求将一个字符串的前n个字符左旋到末尾

可以将这个字符串的前n个字符旋转位置,后n个字符旋转位置

然后此时的字符串以n为分界的字符都已旋转,此时再旋转整体,即可得到左旋后的字符串。

具体步骤为:

  1. 反转区间为前n的子串
  2. 反转区间为n到末尾的子串
  3. 反转整个字符串

代码:(Java)

class Solution {
    public String reverseLeftWords(String s, int n) {
        int len=s.length();
        StringBuilder sb = new StringBuilder(s);
        reverseString(sb,0,n-1);
        reverseString(sb,n,len-1);
        return sb.reverse().toString();
    }

    public void reverseString(StringBuilder sb, int start, int end) {
        while (start < end) {
            char temp = sb.charAt(start);
            sb.setCharAt(start, sb.charAt(end));
            sb.setCharAt(end, temp);
            start++;
            end--;
            }
    }
}

找出字符串中第一个匹配项的下标

https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/

题目:

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。

示例 1:

输入:haystack = "sadbutsad", needle = "sad"
输出:0
解释:"sad" 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。

示例 2:

输入:haystack = "leetcode", needle = "leeto"
输出:-1
解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。

KMP算法:

介绍:https://mp.weixin.qq.com/s?__biz=MzUxNjY5NTYxNA==&mid=2247490330&idx=1&sn=2d648a82ac1127d71918ddc5f09b2835&scene=21#wechat_redirect

思路:

KMP算法的应用,当出现字符串不匹配时,可以记录一部分之前已经匹配的文本内容,利用这些信息避免从头再去做匹配。

代码(Java):

public int strStr(String haystack,String needle){
        if (needle.length() == 0)
            return 0;

        int[] next = new int[needle.length()];
        getNext(next,needle);//得到模式串T前缀表

        //与字符串进行匹配
        int j = -1;
        for (int i = 0; i < haystack.length(); i++) {
            while (j >= 0 && needle.charAt(j+1) != haystack.charAt(i)){
                j = next[j];//回退
            }

            if (needle.charAt(j+1) == haystack.charAt(i))
                j++;

            if (j == needle.length()-1)
                return i - needle.length() + 1;
        }
        return -1;
    }

    public void getNext(int[] next,String s){
        int j = -1;
        next[0] = j;
        for (int i = 1; i < s.length(); i++) {
            while (j >= 0 && s.charAt(j + 1) != s.charAt(i)) {//前后缀不相同
                j = next[j];//回退
            }

            if(s.charAt(j+1) == s.charAt(i))
                j++;//相同,前缀表+1

            next[i] = j; //记录前缀值
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值