实现strstr

题目

实现 strStr() 函数。

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。

 

说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。

 

示例 1:

输入:haystack = "hello", needle = "ll"
输出:2
示例 2:

输入:haystack = "aaaaa", needle = "bba"
输出:-1
示例 3:

输入:haystack = "", needle = ""
输出:0

代码

code

class Solution {
    public int strStr(String haystack, String needle) {
 if (Objects.equals(needle, "") || Objects.equals(haystack,needle)){return 0;}
        if (Objects.equals(haystack, "")){return -1;}
        char [] haystr = haystack.toCharArray();
        char [] neestr = needle.toCharArray();
        int index;
        for (int i = 0 ; i <= haystr.length-neestr.length ; i++){
            index = 0;
            for (int j = 0 ; j < neestr.length;j++){
                if (haystr[i+j] == neestr[j]){index++;}
                if (index == neestr.length){return i;}
            }
        }
        return -1;
    }
}

外观数列

题目

给定一个正整数 n ,输出外观数列的第 n 项。

「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。

你可以将其视作是由递归公式定义的数字字符串序列:

countAndSay(1) = "1"
countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。
前五项如下:

第一项是数字 1
描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 "11"
描述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 "21"
描述前一项,这个数是 21 即 “ 一 个 2 + 一 个 1 ” ,记作 "1211"
描述前一项,这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ,记作 "111221"

作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnpvdm/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

代码

code

class Solution {
    public  static String countAndSay(int n) {
        // 递归出口
        if(n==1){
            return "1";
        }
        // 假设我们获得上一次的结果为 s1 = 112213
        String s1 = countAndSay(n - 1);
        // 定义结果
        StringBuilder result = new StringBuilder();
        // 对s1遍历处理获取值
        char local = s1.charAt(0);
        int count = 0;
        for (int i = 0; i < s1.length(); i++) {
            // 设定计数器 计算同一个数字出现的次数 count
            if(s1.charAt(i) == local){
                count++;
            }else {
                // 不符合,记录下
                result.append(count);
                result.append(local);
                count = 1;
                local = s1.charAt(i);
            }
        }
        result.append(count);
        result.append(local);
        return result.toString();
    }


    public static void main(String[] args) {
        System.out.println(countAndSay(4));
    }
}

END

有问题请联系feinan6666@outlook.com

本文作者:
文章标题:2022-3-2~2022-3-3 力扣刷题记录
本文地址:https://home.cnboy.top/81.html
版权说明:若无注明,本文皆神码人の世界原创,转载请保留文章出处。
最后修改:2022 年 03 月 03 日 06 : 07 PM
如果觉得我的文章对你有用,请随意赞赏