Implement strStr()

  1. /**
     * Implement strStr().
     * 
     * Return the index of the first occurrence of needle in haystack, or -1 if
     * needle is not part of haystack.
     * 
     * 实现Java的indxOf
     */
    public class Lc28 {
        /**
         * 正常的逻辑比较,尽量不使用原来的api
         * 
         * @param haystack
         * @param needle
         * @return
         */
        public static int strStr(String haystack, String needle) {
            boolean haystackIsNUll = "".equals(haystack);
            boolean needleIsNUll = "".equals(needle);
  2.         if (!haystackIsNUll && !needleIsNUll) {
  3.         } else if (!needleIsNUll) {
                return -1;
            } else {
                return 0;
            }
  4.         char chHaystack[] = haystack.toCharArray();
            char chNeedle[] = needle.toCharArray();
  5.         int count = chNeedle.length;
            int temp = 0;
            for (int i = 0; i < chHaystack.length; i++) {
                if (chHaystack[i] == chNeedle[0]) {
                    temp = i;
                    for (int j = 0; j < chNeedle.length && temp < chHaystack.length; j++, temp++) {
                        if (chHaystack[temp] == chNeedle[j]) {
                            count--;
                        } else {
                            break;
                        }
                    }
                }
                if (count == 0) {
                    return i;
                } else {
                    count = chNeedle.length;
                }
            }
            return -1;
        }
  6.     /**
         * 以被比较的字符串作为固定步长,每次直接比较对应长度字符串,比较的次数为俩个字符串的差值。
         * @param haystack
         * @param needle
         * @return
         */
        public static int strStr2(String haystack, String needle) {
            boolean haystackIsNUll = "".equals(haystack);
            boolean needleIsNUll = "".equals(needle);
  7.         if (!haystackIsNUll && !needleIsNUll) {
  8.         } else if (!needleIsNUll) {
                return -1;
            } else {
                return 0;
            }
  9.         char chHaystack[] = haystack.toCharArray();
            char chNeedle[] = needle.toCharArray();
  10.         int len = chHaystack.length - chNeedle.length;
            for (int i = 0; i <= len; i++) {
                if (haystack.substring(i, chNeedle.length + i).equals(needle)) {
                    return i;
                }
            }
            return -1;
        }
  11.     public static void main(String[] args) {
            String haystack = "bbaa";
            String needle = "aab";
    //        System.out.println(strStr(haystack, needle));
            System.out.println(strStr2(haystack, needle));
        }
    }

Longest Common Prefix

  1. /**
     * Write a function to find the longest common prefix string amongst an array of
     * strings.
     * 
     * If there is no common prefix, return an empty string "".
     *
     *找出所有字符串共有的前缀字符出啊
     */
    public class Lc14 {
        public static String longestCommonPrefix(String[] strs) {
            if (strs.length == 0) {
                return "";
            }
  2.         //优化 找到最小长度字符串作为前缀与其他单词比较
            String prefix = strs[0];
            for (int i = 0; i < strs.length; i++) {
                if (prefix.length() > strs[i].length()) {
                    prefix = strs[i];
                }
            }
  3.         //比较前缀和其他单词
            for (int i = 0; i < strs.length; i++) {
                while (strs[i].indexOf(prefix) != 0) {
                    prefix = prefix.substring(0, prefix.length() - 1);
                    if (prefix.isEmpty()) {
                        return "";
                    }
                }
            }
            return prefix;
        }
  4.     public static void main(String[] args) {
            String[] strs = { "flower", "flow", "flight" };
            System.out.println(longestCommonPrefix(strs));
        }
    }

Length of Last Word

  1. /**
     * Given a string s consists of upper/lower-case alphabets and empty space
     * characters ' ', return the length of last word in the string.
     * 
     * If the last word does not exist, return 0.
     * 
     * Note: A word is defined as a character sequence consists of non-space
     * characters only.
     *
     */
    public class Lc58 {
  2.     /*
         * 常规思路:遍历字符串,找到连续的字符个数
         */
        public static int lengthOfLastWord(String s) {
            if (s.length() == 0 || " ".equals(s)) {
                return 0;
            }
  3.         char[] chs = s.trim().toCharArray();
            int len = 0;
            for (int i = 0; i < chs.length; i++) {
                if ((chs[i] >= 'a' && chs[i] <= 'z') || (chs[i] >= 'A' && chs[i] <= 'Z')) {
                    len++;
                } else if (chs[i] == ' '&&i==chs.length-1) {
                    if (len > 0) {
                        return len;
                    }
                }else if(chs[i] == ' '){
                    len = 0;
                }
            }
            return len;
        }
  4.     //利用api直接计算
        public static int lengthOfLastWord1(String s) {
            return s.trim().length() - s.trim().lastIndexOf(" ") - 1;
        }
  5.     public static void main(String[] args) {
            String str = "Today is a nice day";
    //        System.out.println(lengthOfLastWord(str));
            System.out.println(lengthOfLastWord1(str));
        }
    }

First Unique Character in a String

  1. import java.util.LinkedHashMap;
    import java.util.Map;
  2. /**
     * Given a string, find the first non-repeating character in it and return it's
     * index. If it doesn't exist, return -1.
     */
    public class Lc387 {
        /**
         * 通过map存储各个字符出现爱你的个数
         * 注意用linkHashMap,hashmap会自动排序
         * @param s
         * @return
         */
        public static int firstUniqChar(String s) {
            if ("".equals(s)) {
                return -1;
            }
            char[] chs = s.toCharArray();
            Map<Character, Integer> map = new LinkedHashMap<Character, Integer>();
            for (int i = 0; i < chs.length; i++) {
                Character key = chs[i];
                if (map.containsKey(key)) {
                    Integer count = map.get(key);
                    map.put(key, ++count);
                } else {
                    map.put(key, 1);
                }
            }
  3.         Character firstC = ' ';
            for (Map.Entry<Character, Integer> entry : map.entrySet()) {
                if (entry.getValue() == 1) {
                    firstC = entry.getKey();
                    break;
                }
            }
  4.         for (int i = 0; i < chs.length; i++) {
                if (chs[i] == firstC) {
                    return i;
                }
            }
  5.         return -1;
        }
  6.     /**
         * 照比方法优化是使用了api快了几毫秒
         * @param s
         * @return
         */
        public static int firstUniqChar1(String s) {
            if ("".equals(s)) {
                return -1;
            }
            char[] chs = s.toCharArray();
            Map<Character, Integer> map = new LinkedHashMap<Character, Integer>();
            for (int i = 0; i < chs.length; i++) {
                Character key = chs[i];
                if (map.containsKey(key)) {
                    Integer count = map.get(key);
                    map.put(key, ++count);
                } else {
                    map.put(key, 1);
                }
            }
  7.         Character firstC = ' ';
            for (Map.Entry<Character, Integer> entry : map.entrySet()) {
                if (entry.getValue() == 1) {
                    firstC = entry.getKey();
                    break;
                }
            }
            return s.indexOf(firstC);
  8.     }
  9.     public static void main(String[] args) {
            String s = "loveleetcode";
            System.out.println(firstUniqChar(s));
        }
    }

Ransom Note

  1. import java.util.HashMap;
    import java.util.Map;
  2. /**
     * 勒索信
     * 匹配ransomNote中的字符是否能在magazine中找到 
     *
     */
    public class Lc383 {
  3.     public static boolean canConstruct(String ransomNote, String magazine) {
            if (!"".equals(ransomNote) && "".equals(magazine)) {
                return false;
            }
            char[] chs = magazine.toCharArray();
            Map<Character, Integer> map = new HashMap<Character, Integer>();
            for (char key : chs) {
                if (map.containsKey(key)) {
                    Integer count = map.get(key);
                    map.put(key, ++count);
                } else {
                    map.put(key, 1);
                }
            }
  4.         char[] chsRansonNote = ransomNote.toCharArray();
            for (char c : chsRansonNote) {
                int count = 0;
                count = map.get(c) != null ? map.get(c) : 0;
                count--;
                map.put(c, count);
                if (count < 0) {
                    return false;
                }
            }
            return true;
  5.     }
  6.     public static void main(String[] args) {
            String ransomNote = "";
            String magazine = "a";
            System.out.println(canConstruct(ransomNote, magazine));
        }
    }

Reverse String

  1. /**
     *反转字符串 
     *
     */
    public class Lc344 {
        public static void reverseString(char[] s) {
            for (int i = 0; i < Math.round(s.length / 2); i++) {
                char temp = s[i];
                s[i] = s[s.length - 1 - i];
                s[s.length - 1 - i] = temp;
            }
        }
  2.     public static void main(String[] args) {
            char[] s = { 'h', 'e', 'l', 'l', 'o' };
            reverseString(s);
  3.     }
    }

leetcode-字符串篇的更多相关文章

  1. c++ LeetCode (初级字符串篇) 九道算法例题代码详解(二)

    原文作者:aircraft 原文链接:https://www.cnblogs.com/DOMLX/p/11089327.html 已经刷了很多篇leetcode题了,不过最近在找c++的实习工作(大佬 ...

  2. LeetCode 字符串专题(一)

    目录 LeetCode 字符串专题 <c++> \([5]\) Longest Palindromic Substring \([28]\) Implement strStr() [\(4 ...

  3. 【leetcode 字符串处理】Compare Version Numbers

    [leetcode 字符串处理]Compare Version Numbers @author:wepon @blog:http://blog.csdn.net/u012162613 1.题目 Com ...

  4. LeetCode刷题总结-字符串篇

    本文梳理对LeetCode上有关字符串习题的知识点,并给出对应的刷题建议.本文建议刷题的总数为32题.具体知识点如下图: 1.回文问题 题号:5. 最长回文子串,难度中等 题号:214. 最短回文串, ...

  5. Leetcode初级算法(字符串篇)

    目录 反转字符串 颠倒整数 字符串中的第一个唯一字符 有效的字母异位词 验证回文字符串 实现strStr() 数数并说 最长公共前缀 字符串转整数(atoi) 反转字符串 和vector同样的进行sw ...

  6. leetcode 字符串类型题

    1,Vaild Palindrome bool isPalindrome(string& s) { transform(s.begin(), s.end(), s.begin(), tolow ...

  7. leetcode 字符串中的第一个唯一字符

    给定一个字符串,找到它的第一个不重复的字符,并返回它的索引.如果不存在,则返回 -1. 案例: s = "leetcode" 返回 0. s = "loveleetcod ...

  8. leetcode 字符串动态规划总结

    问题1:leetcode 正则表达式匹配 请实现一个函数用来匹配包括'.'和'*'的正则表达式.模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次). 在本题中,匹配 ...

  9. golang基础教程——字符串篇

    本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是golang专题的第6篇文章,这篇主要和大家聊聊golang当中的字符串的使用. 字符串定义 golang当中的字符串本质是只读的字符 ...

  10. C#之字符串篇

    大杂烩 一.类型转换    字符串转整形: int a = int.Parse(""); //不能转换null int b = Convert.ToInt32("&quo ...

随机推荐

  1. maven打包mapper.xml打不进去问题

    <resources> <resource> <directory>src/main/java</directory> <includes> ...

  2. GoLand相同目录(包)下方法调用

    之前写的python,摸索go的时候发现相同目录下写的方法调用,在编译时竟然会报错,Mark~ 相同目录下方法调用,main.go文件调用tool.go中的add方法,要点如下: 1.两个文件的pak ...

  3. 你不知道的JavaScript(上)this和对象原型(四)原型

    五章 原型 1.[[ Prototype ]] JavaScript 中的对象有一个特殊的 [[Prototype]] 内置属性,其实就是对于其他对象的引用.几乎所有的对象在创建时 [[Prototy ...

  4. Java 判断密码是否是大小写字母、数字、特殊字符中的至少三种

    public class CheckPassword { //数字 public static final String REG_NUMBER = ".*\\d+.*"; //小写 ...

  5. OurEDA慕课网开发记录

    项目说明 OurEDA实验室每年都会面向大一新生招人,每周的沙龙都会有学长来讲课,传经验,录下来的沙龙视频就非常有价值,因此,在老师的安排下,我负责开发了慕课网这样一个项目. 首要问题及其解决方案 视 ...

  6. Ubuntu19 安装Theano出现“No module named ‘theano.compat.six’”

    解决办法:直接在下载好pythearn2包的目录下,对setup.py文件进行修改:将  from theano.compat.six.moves import input 改为  from six. ...

  7. day01-day02 初识java、注释、变量、变量命名、基本数据类型

    1. 初识java 1) 什么是java java是一门高级的计算机编程语言 2) JDK的安装 2.1) 下载2.2) 安装2.3) 验证 3) 环境变量的配置 3.1) 打开环境变量3.2) 配置 ...

  8. VS2019 开发Django(三)------连接MySQL

    导航:VS2019开发Django系列 下班回到家,洗漱完毕,夜已深.关于Django这个系列的博文,我心中的想法就是承接之前的微信小程序的内容,做一个服务端的管理中心,上新菜单,调整价格啊!之类的, ...

  9. 记druid 在配置中心下的一个大坑: cpu 达到 100%

    把我们的dubbo 应用移步到配置中心上去之后,发现我们的应用过一段时间就会出现cpu 100%的情况 (大概是12个小时),一开始cpu占用是2-5% 的样子,什么都没做,后面竟然用尽了cpu.. ...

  10. 一步一步搭建 Oracle Data Guard

    前言 为什么要写前言,因为我要吐槽一下.作为一个Java后端,搭建Oracle Data Guard真的是一件,嗯,既不专业也不擅长的事情,然而,为什么还是要我来弄? 因为DBA出差了,我们这边急着要 ...