LeetCode中关于字符串的题目的整理(待更)

检测大写字母(simple难度)

https://leetcode-cn.com/problems/detect-capital/

LeetCode中关于字符串的题目的整理(待更)_第1张图片

本题方法和代码来源:
作者:linaxiaokeai163com
链接:https://leetcode-cn.com/problems/detect-capital/solution/jian-ce-da-xiao-zi-fu-zai-suo-you-java-t-9ibf/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第2张图片

class Solution {
    public boolean detectCapitalUse(String word) {
       boolean res = false;
        int count = 0;
        char x;
        for (int i = 0; i < word.length(); i++) {
            x = word.charAt(i);
            if(x >= 65 && x <= 90) {
                count++;
            }
            // if (word.charAt(i) >= 97 && word.charAt(i) <= 122) {
            // countMin++;
            // }
        }
        if ((count == 1 && (word.charAt(0) >= 65 && word.charAt(0) <= 90)) || (count == word.length())) {
            res = true;
        } else if (count == 0) {
            res = true;
        }
        return res;
    }
}

作者:linaxiaokeai163com
链接:https://leetcode-cn.com/problems/detect-capital/solution/jian-ce-da-xiao-zi-fu-zai-suo-you-java-t-9ibf/
来源:力扣(LeetCode)

反转字符串(simple)

https://leetcode-cn.com/problems/reverse-string/

LeetCode中关于字符串的题目的整理(待更)_第3张图片

class Solution {
    public void reverseString(char[] s) {
        if(s.length == 0){
            return;
        }
        int left = 0;
        int right = s.length - 1;
        while(left < right){
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }
}

反转字符串Ⅱ(simple难度)

https://leetcode-cn.com/problems/reverse-string-ii/

LeetCode中关于字符串的题目的整理(待更)_第4张图片

注意事项:char型数组转换成字符串时不要直接调用toString方法,用Stirng
类的构造器方法来实现。
代码逻辑见注释

class Solution {
    public String reverseStr(String s, int k) {
        char[] charArray = s.toCharArray();
        k >= 字符串长度:直接整个字符串反转
        if (k >= s.length()) {
            return new String(swap(charArray, 0, s.length() - 1));
        }
        int step = 0;
        int len;
        //若下一个2k间隔>=字符串长度,则反转完成
        while (step < s.length()) {
            //len的取值判断防止调用swap方法时发生下标越界
            len = step + k - 1 >= s.length() ? s.length() - 1 : step + k - 1;
            反转[step,len]范围内的元素
            charArray = swap(charArray, step, len);
            //step:每次增加2*k
            step += 2 * k;
        }
        return new String(charArray);
    }
    //对指定下标范围内的元素进行反转
    private char[] swap(char[] charArray, int left, int right) {
        while (left < right) {
            char temp = charArray[left];
            charArray[left] = charArray[right];
            charArray[right] = temp;
            left++;
            right--;
        }
        return charArray;
    }
}

作者:HIT_whc
链接:https://leetcode-cn.com/problems/reverse-string-ii/solution/javashi-jian-ji-bai-100-by-hit_whc-o8u9/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

翻转字符串里面的单词(medium难度)

https://leetcode-cn.com/problems/reverse-words-in-a-string/

LeetCode中关于字符串的题目的整理(待更)_第5张图片

LeetCode中关于字符串的题目的整理(待更)_第6张图片

LeetCode中关于字符串的题目的整理(待更)_第7张图片

LeetCode中关于字符串的题目的整理(待更)_第8张图片

LeetCode中关于字符串的题目的整理(待更)_第9张图片

LeetCode中关于字符串的题目的整理(待更)_第10张图片

class Solution {
    public String reverseWords(String s) {
        // 除去开头和末尾的空白字符
        s = s.trim();
        // 正则匹配连续的空白字符作为分隔符分割
        List wordList = Arrays.asList(s.split("\\s+"));
        Collections.reverse(wordList);
        return String.join(" ", wordList);
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string/solution/fan-zhuan-zi-fu-chuan-li-de-dan-ci-by-leetcode-sol/
来源:力扣(LeetCode)

本题方法和代码来源:

作者:jyd
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string/solution/151-fan-zhuan-zi-fu-chuan-li-de-dan-ci-shuang-zh-2/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第11张图片

LeetCode中关于字符串的题目的整理(待更)_第12张图片

LeetCode中关于字符串的题目的整理(待更)_第13张图片

LeetCode中关于字符串的题目的整理(待更)_第14张图片

class Solution {
    public String reverseWords(String s) {
        s = s.trim(); // 删除首尾空格
        int j = s.length() - 1, i = j;
        StringBuilder res = new StringBuilder();
        while(i >= 0) {
            while(i >= 0 && s.charAt(i) != ' ') i--; // 搜索首个空格
            res.append(s.substring(i + 1, j + 1) + " "); // 添加单词
            while(i >= 0 && s.charAt(i) == ' ') i--; // 跳过单词间空格
            j = i; // j 指向下个单词的尾字符
        }
        return res.toString().trim(); // 转化为字符串并返回
    }
}

作者:jyd
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string/solution/151-fan-zhuan-zi-fu-chuan-li-de-dan-ci-shuang-zh-2/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第15张图片

LeetCode中关于字符串的题目的整理(待更)_第16张图片

class Solution {
    public String reverseWords(String s) {
        String[] strs = s.trim().split(" "); // 删除首尾空格,分割字符串
        StringBuilder res = new StringBuilder();
        for(int i = strs.length - 1; i >= 0; i--) { // 倒序遍历单词列表
            if(strs[i].equals("")) continue; // 遇到空单词则跳过
            res.append(strs[i] + " "); // 将单词拼接至 StringBuilder
        }
        return res.toString().trim(); // 转化为字符串,删除尾部空格,并返回
    }
}

作者:jyd
链接:https://leetcode-cn.com/problems/reverse-words-in-a-string/solution/151-fan-zhuan-zi-fu-chuan-li-de-dan-ci-shuang-zh-2/
来源:力扣(LeetCode)

反转字符串中的单词Ⅲ(simple难度)

https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/

LeetCode中关于字符串的题目的整理(待更)_第17张图片

class Solution {
    public String reverseWords(String s) {
        char[] sArray = s.toCharArray();
        int i = 0, j = 0;
        while(j < sArray.length){
            //单词开头
            while(i < sArray.length && sArray[i] == ' '){
                i++;
            }
            j = i;
            //单词结尾
            while(j < sArray.length && sArray[j] != ' '){
                j++;
            }
            reverse(sArray, i, j-1);
   
            i = j;
        }
        return String.valueOf(sArray);
    }
    public void reverse(char[] s, int start, int end){
        while(start < end){
            char temp = s[start];
            s[start] = s[end];
            s[end] = temp;
            start++;
            end--;
        }
    }
}

验证回文串(simple难度)

https://leetcode-cn.com/problems/valid-palindrome/

LeetCode中关于字符串的题目的整理(待更)_第18张图片

在原字符串上直接判断

class Solution {
    public boolean isPalindrome(String s) {
        int n = s.length();
        int left = 0, right = n - 1;
        while (left < right) {
            while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
                ++left;
            }
            while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
                --right;
            }
            if (left < right) {
                if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
                    return false;
                }
                ++left;
                --right;
            }
        }
        return true;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/valid-palindrome/solution/yan-zheng-hui-wen-chuan-by-leetcode-solution/
来源:力扣(LeetCode)

最长公共前缀(simple难度)

https://leetcode-cn.com/problems/longest-common-prefix/

LeetCode中关于字符串的题目的整理(待更)_第19张图片

LeetCode中关于字符串的题目的整理(待更)_第20张图片

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0) 
            return "";
        String ans = strs[0];
        for(int i =1;i

时间击败100%的算法

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0){
            return "";
        }
        String target = strs[0];
        for (int i = 1; i < strs.length; i++) {
            while (!strs[i].startsWith(target)){
                target = target.substring(0,target.length()-1);
                if (target.length()==0){
                    return "";
                }
                if (strs[i].startsWith(target)){
                    break;
                }
            }
        }
        return target;
    }
}

字符串中的单词数(simple难度)

https://leetcode-cn.com/problems/number-of-segments-in-a-string/

LeetCode中关于字符串的题目的整理(待更)_第21张图片

<方法一>:单指针

class Solution {
    public int countSegments(String s) {
        int segmentCount = 0;

        for (int i = 0; i < s.length(); i++) {
            if ((i == 0 || s.charAt(i-1) == ' ') && s.charAt(i) != ' ') {
                segmentCount++;
            }
        }

        return segmentCount;
    }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/number-of-segments-in-a-string/solution/zi-fu-chuan-zhong-de-dan-ci-shu-by-leetcode/
来源:力扣(LeetCode)

<方法二>:双指针

class Solution {
    public int countSegments(String s) {
        //去除掉前后空格,力扣有测试用例:"          "
        s = s.trim();
        //长度为0或者1直接返回
        if(s.length() == 0 ||s.length() == 1){
            return s.length();
        }
        int res = 0;
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left) ==' ' && s.charAt(left - 1) !=' ') {
                res++;
            }
            left++;
            if (s.charAt(right) ==' ' && s.charAt(right + 1) !=' ') {
                res++;
            }
            right--;
        }
        //此时left == right;如果left和right正在指向同一个字符
        //例如:"abc abc abc",此时left和right指向第二个abc的b
        //此时指向的字符不为空,因为第二个abc没有单独被left或right指针遍历完
        //所以res没有记录第二个abc,所以此时res要加1
        if (s.charAt(left) != ' ') {
            res++;
        //例如"abc abcd"
        //此时left指向空字符,right指向a,
        //但此时left刚刚遍历完的单词没有经过判断
        //res没有记录,此时要判断一下
        }else if(s.charAt(left) == ' ' && s.charAt(left - 1) != ' '){
            res++;
        //同上,例如"abcd abc"
        }else if(s.charAt(right) == ' ' && s.charAt(right + 1) != ' ') {
            res++;
        }
        return res;
    }
}


作者:HIT_whc
链接:https://leetcode-cn.com/problems/number-of-segments-in-a-string/solution/javashuang-zhi-zhen-shi-jian-ji-bai-100-fzdof/
来源:力扣(LeetCode)

最后一个单词的长度(simple难度)

https://leetcode-cn.com/problems/length-of-last-word/

LeetCode中关于字符串的题目的整理(待更)_第22张图片

本题方法和代码来源:
作者:guanpengchn
链接:https://leetcode-cn.com/problems/length-of-last-word/solution/hua-jie-suan-fa-58-zui-hou-yi-ge-dan-ci-de-chang-d/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第23张图片

class Solution {
    public int lengthOfLastWord(String s) {
        int end = s.length() - 1;
        while(end >= 0 && s.charAt(end) == ' ') end--;
        if(end < 0) return 0;
        int start = end;
        while(start >= 0 && s.charAt(start) != ' ') start--;
        return end - start;
    }
}

作者:guanpengchn
链接:https://leetcode-cn.com/problems/length-of-last-word/solution/hua-jie-suan-fa-58-zui-hou-yi-ge-dan-ci-de-chang-d/
来源:力扣(LeetCode)

字符串中的第一个唯一的字符(simple难度)

https://leetcode-cn.com/problems/first-unique-character-in-a-string/

LeetCode中关于字符串的题目的整理(待更)_第24张图片

本题方法和代码来源:
作者:sdwwld
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/solution/javaduo-chong-fang-shi-jie-jue-by-sdwwld-iojm/
来源:力扣(LeetCode)

    public int firstUniqChar(String s) {
        int count[] = new int[26];
        char[] chars = s.toCharArray();
        //先统计每个字符出现的次数
        for (int i = 0; i < s.length(); i++)
            count[chars[i] - 'a']++;
        //然后在遍历字符串s中的字符,如果出现次数是1就直接返回
        for (int i = 0; i < s.length(); i++)
            if (count[chars[i] - 'a'] == 1)
                return i;
        return -1;
    }

作者:sdwwld
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/solution/javaduo-chong-fang-shi-jie-jue-by-sdwwld-iojm/
来源:力扣(LeetCode)

    public int firstUniqChar(String s) {
        Map map = new HashMap();
        char[] chars = s.toCharArray();
        //先统计每个字符的数量
        for (char ch : chars) {
            map.put(ch, map.getOrDefault(ch, 0) + 1);
        }
        //然后在遍历字符串s中的字符,如果出现次数是1就直接返回
        for (int i = 0; i < s.length(); i++) {
            if (map.get(chars[i]) == 1) {
                return i;
            }
        }
        return -1;
    }

作者:sdwwld
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/solution/javaduo-chong-fang-shi-jie-jue-by-sdwwld-iojm/
来源:力扣(LeetCode)

    public int firstUniqChar(String s) {
        for (int i = 0; i < s.length(); i++)
            if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i)))
                return i;
        return -1;
    }

作者:sdwwld
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/solution/javaduo-chong-fang-shi-jie-jue-by-sdwwld-iojm/
来源:力扣(LeetCode)

找不同(simple难度)

https://leetcode-cn.com/problems/find-the-difference/

LeetCode中关于字符串的题目的整理(待更)_第25张图片

LeetCode中关于字符串的题目的整理(待更)_第26张图片

本题方法和代码来源:
作者:sweetiee
链接:https://leetcode-cn.com/problems/find-the-difference/solution/yi-ju-hua-zhao-bu-tong-reduce-gao-qi-lai-eqok/
来源:力扣(LeetCode)

class Solution {
    public char findTheDifference(String s, String t) {
        char res = 0;
        for (char c: s.toCharArray()) {
            res ^= c;
        }
        for (char c: t.toCharArray()) {
            res ^= c;
        }
        return res;
    }
}

作者:sweetiee
链接:https://leetcode-cn.com/problems/find-the-difference/solution/yi-ju-hua-zhao-bu-tong-reduce-gao-qi-lai-eqok/
来源:力扣(LeetCode)

java炫技:

LeetCode中关于字符串的题目的整理(待更)_第27张图片

class Solution {
    public char findTheDifference(String s, String t) {
        return (char)(s + t).chars().reduce(0, (a, b) -> a ^ b);
    }
}

作者:sweetiee
链接:https://leetcode-cn.com/problems/find-the-difference/solution/yi-ju-hua-zhao-bu-tong-reduce-gao-qi-lai-eqok/
来源:力扣(LeetCode)

赎金信(simple难度)

https://leetcode-cn.com/problems/ransom-note/

LeetCode中关于字符串的题目的整理(待更)_第28张图片

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        if (ransomNote.length() == 0) {
            return true;
        }
        if (magazine.length() == 0) {
            return false;
        }
        int[] count = new int[26];
        char[] magazineArray = magazine.toCharArray();
        //统计magazine中各个字符出现的次数并放在数组中
        for (int i = 0; i < magazineArray.length; i++) {
            count[magazineArray[i] - 'a']++;
        }
        char[] ransomNoteArray = ransomNote.toCharArray();
        //判断magazine中各个字符的个数能否满足ransomNote的需要
        for (int i = 0; i < ransomNoteArray.length; i++) {
            //如果当前ransomNote需要的字符已经被用完,则返回false
            if (count[ransomNoteArray[i] - 'a'] == 0) {
                return false;
            } else {
                count[ransomNoteArray[i] - 'a']--;
            }
        }
        return true;
    }
}


作者:HIT_whc
链接:https://leetcode-cn.com/problems/ransom-note/solution/javashu-zu-jie-fa-by-hit_whc-x3id/
来源:力扣(LeetCode)

有效的字母异位词(simple难度)

https://leetcode-cn.com/problems/valid-anagram/

LeetCode中关于字符串的题目的整理(待更)_第29张图片

本题方法和代码来源:
作者:guanpengchn
链接:https://leetcode-cn.com/problems/valid-anagram/solution/hua-jie-suan-fa-242-you-xiao-de-zi-mu-yi-wei-ci-by/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第30张图片

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length())
            return false;
        int[] alpha = new int[26];
        for(int i = 0; i< s.length(); i++) {
            alpha[s.charAt(i) - 'a'] ++;
            alpha[t.charAt(i) - 'a'] --;
        }
        for(int i=0;i<26;i++)
            if(alpha[i] != 0)
                return false;
        return true;
    }
}

作者:guanpengchn
链接:https://leetcode-cn.com/problems/valid-anagram/solution/hua-jie-suan-fa-242-you-xiao-de-zi-mu-yi-wei-ci-by/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第31张图片

class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        Map table = new HashMap();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            table.put(ch, table.getOrDefault(ch, 0) + 1);
        }
        for (int i = 0; i < t.length(); i++) {
            char ch = t.charAt(i);
            table.put(ch, table.getOrDefault(ch, 0) - 1);
            if (table.get(ch) < 0) {
                return false;
            }
        }
        return true;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/valid-anagram/solution/you-xiao-de-zi-mu-yi-wei-ci-by-leetcode-solution/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第32张图片

排序 :(最快的方法)

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
            return false;
        char [] sArray=s.toCharArray();
         char [] tArray=t.toCharArray();
        Arrays.sort(sArray);
        Arrays.sort(tArray);
        String ss=String.valueOf(sArray);
        String tt=String.valueOf(tArray);
        return ss.equals(tt);
    }
}

从英文中重建数字(medium难度)

https://leetcode-cn.com/problems/reconstruct-original-digits-from-english/

LeetCode中关于字符串的题目的整理(待更)_第33张图片

本题方法和代码来源:
作者:romantic-tesla
链接:https://leetcode-cn.com/problems/reconstruct-original-digits-from-english/solution/zhao-dao-shu-zi-dui-ying-de-ying-wen-zi-kdxkz/
来源:力扣(LeetCode)

class Solution {
    public String originalDigits(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        int[] num = new int[10];
        int len = s.length();
        int[] alpha = new int[26];
        for (int i = 0; i < len; i++) {
            alpha[s.charAt(i) - 'a']++;
        }
        num[0] = alpha['z' - 'a'];
        num[2] = alpha['w' - 'a'];
        num[4] = alpha['u' - 'a'];
        num[6] = alpha['x' - 'a'];
        num[8] = alpha['g' - 'a'];
        num[5] = alpha['f' - 'a'] - num[4];
        num[3] = alpha['h' - 'a'] - num[8];
        num[7] = alpha['s' - 'a'] - num[6];
        num[9] = alpha['i' - 'a'] - num[5] - num[6] - num[8];
        num[1] = alpha['n' - 'a'] - num[7] - 2 * num[9];
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            int count = num[i];
            for (int j = 0; j < count; j++) {
                stringBuilder.append((char) ('0' + i));
            }
        }
        return stringBuilder.toString();
    }
}

作者:romantic-tesla
链接:https://leetcode-cn.com/problems/reconstruct-original-digits-from-english/solution/zhao-dao-shu-zi-dui-ying-de-ying-wen-zi-kdxkz/
来源:力扣(LeetCode)

猜数字游戏(medium难度)

https://leetcode-cn.com/problems/bulls-and-cows/

LeetCode中关于字符串的题目的整理(待更)_第34张图片

本题方法和代码来源:
作者:zyxwmj
链接:https://leetcode-cn.com/problems/bulls-and-cows/solution/yi-ci-bian-li-1-ms-10000-by-zyxwmj-d5sa/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第35张图片

class Solution {
    public String getHint(String secret, String guess) {
        // secretArray 和 guessArray 分别记录 两个字符串中非公牛的各个数字的数量
        int[] secretArray = new int[10];
        int[] guessArray = new int[10];
        // 公牛
        int A = 0;
        for (int i = 0; i < secret.length(); i++) {
            // 如果同位的数字相等则,公牛++
            if (secret.charAt(i) == guess.charAt(i)) {
                A++;
            } else {
                secretArray[secret.charAt(i) - '0']++;
                guessArray[guess.charAt(i) - '0']++;
            }
        }
        // 奶牛
        int B = 0;
        for (int i = 0; i < 10; i++) {
            // 不同位上的相同数字的数量
            B += Math.min(secretArray[i], guessArray[i]);
        }
        StringBuilder stringBuilder = new StringBuilder();
        return stringBuilder.append(A).append('A').append(B).append('B').toString();
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/bulls-and-cows/solution/yi-ci-bian-li-1-ms-10000-by-zyxwmj-d5sa/
来源:力扣(LeetCode)

class Solution {

    public String getHint(String secret, String guess) {
        int[] array = new int[10];
        int A = 0, B = 0;
        for (int i = 0; i < secret.length(); i++) {
            if (secret.charAt(i) == guess.charAt(i)) {
                A++;
            } else {
                // 判断 guess 在 i 之前是否该数字
                if (array[secret.charAt(i) - '0']++ < 0) {
                    B++;
                }
                // 判断 secret 在 i 之前是否该数字
                if (array[guess.charAt(i) - '0']-- > 0) {
                    B++;
                }
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        return stringBuilder.append(A).append('A').append(B).append('B').toString();
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/bulls-and-cows/solution/yi-ci-bian-li-1-ms-10000-by-zyxwmj-d5sa/
来源:力扣(LeetCode)

Fizz Buzz(simple难度)

https://leetcode-cn.com/problems/fizz-buzz/

LeetCode中关于字符串的题目的整理(待更)_第36张图片

LeetCode中关于字符串的题目的整理(待更)_第37张图片

LeetCode中关于字符串的题目的整理(待更)_第38张图片

class Solution {
  public List fizzBuzz(int n) {

    // ans list
    List ans = new ArrayList();

    for (int num = 1; num <= n; num++) {

      boolean divisibleBy3 = (num % 3 == 0);
      boolean divisibleBy5 = (num % 5 == 0);

      if (divisibleBy3 && divisibleBy5) {
        // Divides by both 3 and 5, add FizzBuzz
        ans.add("FizzBuzz");
      } else if (divisibleBy3) {
        // Divides by 3, add Fizz
        ans.add("Fizz");
      } else if (divisibleBy5) {
        // Divides by 5, add Buzz
        ans.add("Buzz");
      } else {
        // Not divisible by 3 or 5, add the number
        ans.add(Integer.toString(num));
      }
    }

    return ans;
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/fizz-buzz/solution/fizz-buzz-by-leetcode/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第39张图片

LeetCode中关于字符串的题目的整理(待更)_第40张图片

LeetCode中关于字符串的题目的整理(待更)_第41张图片

class Solution {
  public List fizzBuzz(int n) {
    // ans list
    List ans = new ArrayList();

    for (int num = 1; num <= n; num++) {

      boolean divisibleBy3 = (num % 3 == 0);
      boolean divisibleBy5 = (num % 5 == 0);

      String numAnsStr = "";

      if (divisibleBy3) {
        // Divides by 3, add Fizz
        numAnsStr += "Fizz";
      }

      if (divisibleBy5) {
        // Divides by 5, add Buzz
        numAnsStr += "Buzz";
      }

      if (numAnsStr.equals("")) {
        // Not divisible by 3 or 5, add the number
        numAnsStr += Integer.toString(num);
      }

      // Append the current answer str to the ans list
      ans.add(numAnsStr);
    }

    return ans;
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/fizz-buzz/solution/fizz-buzz-by-leetcode/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第42张图片

LeetCode中关于字符串的题目的整理(待更)_第43张图片

LeetCode中关于字符串的题目的整理(待更)_第44张图片

class Solution {
  public List fizzBuzz(int n) {

    // ans list
    List ans = new ArrayList();

    // Hash map to store all fizzbuzz mappings.
    HashMap fizzBizzDict =
        new HashMap() {
          {
            put(3, "Fizz");
            put(5, "Buzz");
          }
        };

    for (int num = 1; num <= n; num++) {

      String numAnsStr = "";

      for (Integer key : fizzBizzDict.keySet()) {

        // If the num is divisible by key,
        // then add the corresponding string mapping to current numAnsStr
        if (num % key == 0) {
          numAnsStr += fizzBizzDict.get(key);
        }
      }

      if (numAnsStr.equals("")) {
        // Not divisible by 3 or 5, add the number
        numAnsStr += Integer.toString(num);
      }

      // Append the current answer str to the ans list
      ans.add(numAnsStr);
    }

    return ans;
  }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/fizz-buzz/solution/fizz-buzz-by-leetcode/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第45张图片

相对名次(simple难度)

https://leetcode-cn.com/problems/relative-ranks/

LeetCode中关于字符串的题目的整理(待更)_第46张图片

LeetCode中关于字符串的题目的整理(待更)_第47张图片

本题方法和代码来源:
作者:zyxwmj
链接:https://leetcode-cn.com/problems/relative-ranks/solution/san-chong-jie-fa-ji-shu-pai-xu-2-ms10000-ml6v/
来源:力扣(LeetCode)

class Solution {
    public String[] findRelativeRanks(int[] nums) {
        int n = nums.length;
        int[] array = new int[n];
        // 拷贝数组
        System.arraycopy(nums, 0, array, 0, n);
        // 对数组进行排序
        Arrays.sort(array);
        String[] result = new String[n];
        for (int i = 0; i < n; i++) {
            // 查找当前成绩排第几名
            int index = n - Arrays.binarySearch(array, nums[i]);
            switch (index) {
                case 1:
                    result[i] = "Gold Medal";
                    break;
                case 2:
                    result[i] = "Silver Medal";
                    break;
                case 3:
                    result[i] = "Bronze Medal";
                    break;
                default:
                    result[i] = String.valueOf(index);
            }
        }
        return result;
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/relative-ranks/solution/san-chong-jie-fa-ji-shu-pai-xu-2-ms10000-ml6v/
来源:力扣(LeetCode)

class Solution {
    public String[] findRelativeRanks(int[] nums) {
        int n = nums.length;
        String[] result = new String[n];
        int max = 0;
        // 找出找出最高的成绩
        for (int num : nums) {
            if (max < num) {
                max = num;
            }
        }
        // 下标为成绩,值为成绩在 nums 数组的下标
        int[] array = new int[max + 1];
        for (int i = 0; i < n; i++) {
            array[nums[i]] = i + 1;
        }
        // 记录当前成绩的排名
        int count = 1;
        for (int i = array.length - 1; i >= 0; i--) {
            if (array[i] != 0) {
                // 根据排名进行赋值
                switch (count) {
                    case 1:
                        result[array[i] - 1] = "Gold Medal";
                        break;
                    case 2:
                        result[array[i] - 1] = "Silver Medal";
                        break;
                    case 3:
                        result[array[i] - 1] = "Bronze Medal";
                        break;
                    default:
                        result[array[i] - 1] = String.valueOf(count);
                }
                count++;
            }
        }
        return result;
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/relative-ranks/solution/san-chong-jie-fa-ji-shu-pai-xu-2-ms10000-ml6v/
来源:力扣(LeetCode)

外观数列(simple难度)

https://leetcode-cn.com/problems/count-and-say/

LeetCode中关于字符串的题目的整理(待更)_第48张图片

LeetCode中关于字符串的题目的整理(待更)_第49张图片

LeetCode中关于字符串的题目的整理(待更)_第50张图片

本题方法和代码来源:
作者:zyxwmj
链接:https://leetcode-cn.com/problems/count-and-say/solution/xun-huan-he-di-gui-liang-chong-jie-fa-di-oof8/
来源:力扣(LeetCode)

class Solution {
    public String countAndSay(int n) {
        // 递归终止条件
        if (n == 1) {
            return "1";
        }
        // 获取到上一层的字符串
        String s = countAndSay(n - 1);
        StringBuilder result = new StringBuilder();
        // 记录每个数字的开始索引
        int start = 0;
        for (int i = 1; i < s.length(); i++) {
            // 当数字发生改变时执行
            if (s.charAt(i) != s.charAt(start)) {
                result.append(i - start).append(s.charAt(start));
                start = i;
            }
        }
        // 字符串最后一个数字
        result.append(s.length() - start).append(s.charAt(start));
        return result.toString();
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/count-and-say/solution/xun-huan-he-di-gui-liang-chong-jie-fa-di-oof8/
来源:力扣(LeetCode)

压缩字符串(medium难度)

https://leetcode-cn.com/problems/string-compression/

LeetCode中关于字符串的题目的整理(待更)_第51张图片

LeetCode中关于字符串的题目的整理(待更)_第52张图片

LeetCode中关于字符串的题目的整理(待更)_第53张图片

class Solution {
    public int compress(char[] chars) {
        int anchor = 0, write = 0;
        for (int read = 0; read < chars.length; read++) {
            if (read + 1 == chars.length || chars[read + 1] != chars[read]) {
                chars[write++] = chars[anchor];
                if (read > anchor) {
                    for (char c: ("" + (read - anchor + 1)).toCharArray()) {
                        chars[write++] = c;
                    }
                }
                anchor = read + 1;
            }
        }
        return write;
    }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/string-compression/solution/ya-suo-zi-fu-chuan-by-leetcode/
来源:力扣(LeetCode)

判断子序列(simple难度)

https://leetcode-cn.com/problems/is-subsequence/

LeetCode中关于字符串的题目的整理(待更)_第54张图片

LeetCode中关于字符串的题目的整理(待更)_第55张图片

LeetCode中关于字符串的题目的整理(待更)_第56张图片

class Solution {
    public boolean isSubsequence(String s, String t) {
        int n = s.length(), m = t.length();
        int i = 0, j = 0;
        while (i < n && j < m) {
            if (s.charAt(i) == t.charAt(j)) {
                i++;
            }
            j++;
        }
        return i == n;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/is-subsequence/solution/pan-duan-zi-xu-lie-by-leetcode-solution/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第57张图片

LeetCode中关于字符串的题目的整理(待更)_第58张图片

class Solution {
    public boolean isSubsequence(String s, String t) {
        int n = s.length(), m = t.length();

        int[][] f = new int[m + 1][26];
        for (int i = 0; i < 26; i++) {
            f[m][i] = m;
        }

        for (int i = m - 1; i >= 0; i--) {
            for (int j = 0; j < 26; j++) {
                if (t.charAt(i) == j + 'a')
                    f[i][j] = i;
                else
                    f[i][j] = f[i + 1][j];
            }
        }
        int add = 0;
        for (int i = 0; i < n; i++) {
            if (f[add][s.charAt(i) - 'a'] == m) {
                return false;
            }
            add = f[add][s.charAt(i) - 'a'] + 1;
        }
        return true;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/is-subsequence/solution/pan-duan-zi-xu-lie-by-leetcode-solution/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第59张图片

通过删除字母匹配到字典里最长的单词(medium难度)

https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting/

LeetCode中关于字符串的题目的整理(待更)_第60张图片

本题方法和代码来源:
作者:zyxwmj
链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting/solution/fei-jing-xin-si-xie-de-dong-tai-gui-hua-xu2o9/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第61张图片

class Solution {

    public boolean isSubsequence(String t, String s) {
        int indext = 0, indexs = 0;
        while (indext < t.length() && indexs < s.length()) {
            if (t.charAt(indext) == s.charAt(indexs)) {
                indext++;
            }
            indexs++;
        }
        return indext == t.length();
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting/solution/fei-jing-xin-si-xie-de-dong-tai-gui-hua-xu2o9/
来源:力扣(LeetCode)

class Solution {
    
    public boolean isSubsequence(String t, String s) {
        int index = -1;
        for (int i = 0; i < t.length(); i++) {
            index = s.indexOf(t.charAt(i), index + 1);
            if (index == -1) {
                return false;
            }
        }
        return true;
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting/solution/fei-jing-xin-si-xie-de-dong-tai-gui-hua-xu2o9/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第62张图片

class Solution {

    public boolean isSubsequence(String t, String s) {
        int n = s.length();
        int[][] dp = new int[n + 1][26];
        // 初始化结尾
        for (int i = 0; i < 26; i++) {
            dp[n][i] = n;
        }
        // 初始化 dp 数组
        for (int i = n - 1; i >= 0; i--) {
            for (int j = 0; j < 26; j++) {
                if (s.charAt(i) - 'a' == j) {
                    dp[i][j] = i;
                } else {
                    // 不相等,则继承上一位的值
                    dp[i][j] = dp[i + 1][j];
                }
            }
        }
        int index = 0;
        for (char c : t.toCharArray()) {
            // 如果下一个字符在结尾,则表示 s 中没有该字符
            if (dp[index][c - 'a'] == n) {
                return false;
            }
            // 移动到下一个字符的后面
            index = dp[index][c - 'a'] + 1;
        }
        return true;
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting/solution/fei-jing-xin-si-xie-de-dong-tai-gui-hua-xu2o9/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第63张图片

class Solution {

    public String findLongestWord(String s, List d) {
        String result = "";
        for (String t : d) {
            if (isSubsequence(t, s)) {
                // 获取长度最长且字典顺序最小的字符串
                if (result.length() < t.length() || (result.length() == t.length() && result.compareTo(t) > 0)) {
                    result = t;
                }
            }
        }
        return result;
    }

    // 判断 t 是否为 s 的子序列
    public boolean isSubsequence(String t, String s) {
        int indext = 0, indexs = 0;
        while (indext < t.length() && indexs < s.length()) {
            if (t.charAt(indext) == s.charAt(indexs)) {
                indext++;
            }
            indexs++;
        }
        return indext == t.length();
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting/solution/fei-jing-xin-si-xie-de-dong-tai-gui-hua-xu2o9/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第64张图片

class Solution {
    
    public String findLongestWord(String s, List d) {
        String result = "";
        for (String t : d) {
            if (isSubsequence(t, s)) {
                // 获取长度最长且字典顺序最小的字符串
                if (result.length() < t.length() || (result.length() == t.length() && result.compareTo(t) > 0)) {
                    result = t;
                }
            }
        }
        return result;
    }

    // 判断 t 是否为 s 的子序列
    public boolean isSubsequence(String t, String s) {
        int index = -1;
        for (int i = 0; i < t.length(); i++) {
            index = s.indexOf(t.charAt(i), index + 1);
            if (index == -1) {
                return false;
            }
        }
        return true;
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting/solution/fei-jing-xin-si-xie-de-dong-tai-gui-hua-xu2o9/
来源:力扣(LeetCode

LeetCode中关于字符串的题目的整理(待更)_第65张图片

class Solution {

    public String findLongestWord(String s, List d) {
        int n = s.length();
        int[][] dp = new int[n + 1][26];
        // 初始化结尾
        for (int i = 0; i < 26; i++) {
            dp[n][i] = n;
        }
        // 初始化 dp 数组
        for (int i = n - 1; i >= 0; i--) {
            for (int j = 0; j < 26; j++) {
                if (s.charAt(i) - 'a' == j) {
                    dp[i][j] = i;
                } else {
                    dp[i][j] = dp[i + 1][j];
                }
            }
        }
        String result = "";
        for (String t : d) {
            // count 记录相等字符的个数
            int count = 0, index = 0;
            for (char c : t.toCharArray()) {
                // 如果下一个字符的下标为 n,则表示该字符不存在
                if (dp[index][c - 'a'] == n) {
                    break;
                }
                count++;
                // 移动到下一个字符的后面
                index = dp[index][c - 'a'] + 1;
            }
            // 判断是否到了最后一个字符
            if (count == t.length()) {
                // 长度最长且字典顺序最小的字符串
                if (t.length() > result.length() || (t.length() == result.length() && result.compareTo(t) > 0)) {
                    result = t;
                }
            }
        }
        return result;
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting/solution/fei-jing-xin-si-xie-de-dong-tai-gui-hua-xu2o9/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

加一(simple难度)

https://leetcode-cn.com/problems/plus-one/

LeetCode中关于字符串的题目的整理(待更)_第66张图片

本题方法和代码来源:
作者:yhhzw
链接:https://leetcode-cn.com/problems/plus-one/solution/java-shu-xue-jie-ti-by-yhhzw/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第67张图片

class Solution {
    public int[] plusOne(int[] digits) {
        for (int i = digits.length - 1; i >= 0; i--) {
            digits[i]++;
            digits[i] = digits[i] % 10;
            if (digits[i] != 0) return digits;
        }
        digits = new int[digits.length + 1];
        digits[0] = 1;
        return digits;
    }
}

作者:yhhzw
链接:https://leetcode-cn.com/problems/plus-one/solution/java-shu-xue-jie-ti-by-yhhzw/
来源:力扣(LeetCode)

二进制求和(simple难度)

https://leetcode-cn.com/problems/add-binary/

LeetCode中关于字符串的题目的整理(待更)_第68张图片

本题方法和代码来源:
作者:guanpengchn
链接:https://leetcode-cn.com/problems/add-binary/solution/hua-jie-suan-fa-67-er-jin-zhi-qiu-he-by-guanpengch/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第69张图片

class Solution {
    public String addBinary(String a, String b) {
        StringBuilder ans = new StringBuilder();
        int ca = 0;
        for(int i = a.length() - 1, j = b.length() - 1;i >= 0 || j >= 0; i--, j--) {
            int sum = ca;
            sum += i >= 0 ? a.charAt(i) - '0' : 0;
            sum += j >= 0 ? b.charAt(j) - '0' : 0;
            ans.append(sum % 2);
            ca = sum / 2;
        }
        ans.append(ca == 1 ? ca : "");
        return ans.reverse().toString();
    }
}

作者:guanpengchn
链接:https://leetcode-cn.com/problems/add-binary/solution/hua-jie-suan-fa-67-er-jin-zhi-qiu-he-by-guanpengch/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第70张图片

字符串相加(simple难度)

https://leetcode-cn.com/problems/add-strings/

LeetCode中关于字符串的题目的整理(待更)_第71张图片

class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder res = new StringBuilder();
        int ca = 0;
        for (int i = num1.length()-1, j = num2.length()-1; i >= 0 || j >= 0; i--, j--) {
            int sum = ca;
            sum += i >= 0 ? num1.charAt(i) - '0' : 0;
            sum += j >= 0 ? num2.charAt(j) - '0' : 0;
            res.append(sum % 10);
            ca = sum / 10;
        }
        res.append(ca == 1 ? ca : "");
        return res.reverse().toString();
    }
}

密钥格式化(simple难度)

https://leetcode-cn.com/problems/license-key-formatting/

LeetCode中关于字符串的题目的整理(待更)_第72张图片

本题方法和代码来源:
作者:zyxwmj
链接:https://leetcode-cn.com/problems/license-key-formatting/solution/liang-chong-jie-fa-shi-yong-char-4-ms990-xrpo/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第73张图片

class Solution {
    public String licenseKeyFormatting(String S, int K) {
        StringBuilder s = new StringBuilder();
        // 统计已打印字符个数
        int count = 0;
        // 倒序遍历字符串
        for (int i = S.length() - 1; i >= 0; i--) {
            if (S.charAt(i) != '-') {
                // 计算什么时候打印分隔符
                if (count != 0 && count % K == 0) {
                    s.append('-');
                }
                // 转为大写字母添加
                s.append(Character.toUpperCase(S.charAt(i)));
                count++;
            }
        }
        // 反转字符串
        return s.reverse().toString();
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/license-key-formatting/solution/liang-chong-jie-fa-shi-yong-char-4-ms990-xrpo/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第74张图片

class Solution {
    public String licenseKeyFormatting(String S, int K) {
        char[] array = S.toCharArray();
        // 统计字符的个数
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] != '-') {
                // 将小写字符转为大写字符
                if (array[i] > 'Z') {
                    array[i] -= 32;
                }
                count++;
            }
        }
        // 没有字符返回空串
        if (count == 0) {
            return "";
        }
        // 计算分隔符的个数
        int separator = count / K;
        // 如果正好整除,分隔符个数 - 1
        separator = count % K == 0 ? separator - 1 : separator;
        // 存储结果的数组
        char[] result = new char[count + separator];
        // 指向结果数组的下标,倒序赋值
        int index = result.length - 1;
        // 统计已打印字符个数
        int letter = 0;
        for (int i = S.length() - 1; i >= 0; i--) {
            if (array[i] != '-') {
                // 计算什么时候打印分隔符
                if (letter != 0 && letter % K == 0) {
                    result[index--] = '-';
                }
                result[index--] = array[i];
                letter++;
            }
        }
        return new String(result);
    }
}

作者:zyxwmj
链接:https://leetcode-cn.com/problems/license-key-formatting/solution/liang-chong-jie-fa-shi-yong-char-4-ms990-xrpo/
来源:力扣(LeetCode)

Z字形变换(medium难度)

https://leetcode-cn.com/problems/zigzag-conversion/

LeetCode中关于字符串的题目的整理(待更)_第75张图片

LeetCode中关于字符串的题目的整理(待更)_第76张图片

本题方法和代码来源:
作者:jyd
链接:https://leetcode-cn.com/problems/zigzag-conversion/solution/zzi-xing-bian-huan-by-jyd/
来源:力扣(LeetCode)

LeetCode中关于字符串的题目的整理(待更)_第77张图片

LeetCode中关于字符串的题目的整理(待更)_第78张图片

LeetCode中关于字符串的题目的整理(待更)_第79张图片

class Solution {
    public String convert(String s, int numRows) {
        if(numRows < 2) return s;
        List rows = new ArrayList();
        for(int i = 0; i < numRows; i++) rows.add(new StringBuilder());
        int i = 0, flag = -1;
        for(char c : s.toCharArray()) {
            rows.get(i).append(c);
            if(i == 0 || i == numRows -1) flag = - flag;
            i += flag;
        }
        StringBuilder res = new StringBuilder();
        for(StringBuilder row : rows) res.append(row);
        return res.toString();
    }
}

作者:jyd
链接:https://leetcode-cn.com/problems/zigzag-conversion/solution/zzi-xing-bian-huan-by-jyd/
来源:力扣(LeetCode)

实现strStr()(simple难度)

https://leetcode-cn.com/problems/implement-strstr/

LeetCode中关于字符串的题目的整理(待更)_第80张图片

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(LeetCode题目分类整理,字符串,leetcode)