美文网首页
字符串基础问题

字符串基础问题

作者: 傅晨明 | 来源:发表于2019-12-04 17:04 被阅读0次

1 转换成小写字母

709. 转换成小写字母

    public String toLowerCase(String str) {
        String ans = "";
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c >= 'A' && c <= 'Z') {
                c = (char) (c + 32);
            }
            ans += c;
        }
        return ans;
    }

    public String toLowerCase2(String str) {
        char[] a = str.toCharArray();
        for (int i = 0; i < a.length; i++)
            if ('A' <= a[i] && a[i] <= 'Z')
                a[i] = (char) (a[i] - 'A' + 'a');//不需要知道a和A之间相差32
        return new String(a);
    }

2 最后一个单词的长度

58. 最后一个单词的长度


3 宝石与石头

771. 宝石与石头


字符串中的第一个唯一字符

387. 字符串中的第一个唯一字符

    public int firstUniqChar(String s) {
        int[] count = new int[26];// 存储各字符出现次数
        int n = s.length();
        for (int i = 0; i < n; i++) {
            count[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < n; i++) {
            if (count[s.charAt(i) - 'a'] == 1) {
                return i;
            }
        }
        return -1;// 无解
    }

      /**
        * 如果题目要求不仅仅是小写字母,而是任意字符,可以使用HashMap
        */
    public int firstUniqChar(String s) {
        HashMap<Character, Integer> count = new HashMap<Character, Integer>();
        int n = s.length();
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            count.put(c, count.getOrDefault(c, 0) + 1);
        }
        for (int i = 0; i < n; i++) {
            if (count.get(s.charAt(i)) == 1) {
                return i;
            }
        }
        return -1;
    }

相关文章

  • 字符串基础问题

    https://leetcode-cn.com/problems/to-lower-case/ https://l...

  • 字符串基础问题

    题目一 public class Test{ public static void main(String[]...

  • 前端基础(问答14)

    keywords: 数组读写、字符串转化数组、数组转字符串、函数、数学函数、随机数、ES5数组、排序。 问题 基础...

  • [蓝桥杯]FJ的字符串

    问题 1461: [蓝桥杯][基础练习VIP]FJ的字符串 题目描述 FJ在沙盘上写了这样一些字符串: A1 = ...

  • js数据类型

    问题 1. 基础类型有哪些?复杂类型有哪些?有什么特征? 基础类型: 数字、字符串、布尔型、Null、Undefi...

  • Vue使用问题记录

    Vue使用中遇到的问题总结记录。内容比较基础,无奈我是菜鸟 1、Vue中字符串换行不起作用 content字符串很...

  • 你所不知道的Python | 字符串连接的秘密

    字符串连接,就是将2个或以上的字符串合并成一个,看上去连接字符串是一个非常基础的小问题,但是在Python中,我们...

  • Python 字符串连接方式有这些,你了解过吗?

    字符串连接,就是将2个或以上的字符串合并成一个,看上去连接字符串是一个非常基础的小问题,但是在Python中,我们...

  • Python 字符串连接方式有这么种,你知道吗?

    字符串连接,就是将2个或以上的字符串合并成一个,看上去连接字符串是一个非常基础的小问题,但是在Python中,我们...

  • [蓝桥杯]字符串对比

    问题 1466: [蓝桥杯][基础练习VIP]字符串对比 题目描述 给定两个仅由大写字母或小写字母组成的字符串(长...

网友评论

      本文标题:字符串基础问题

      本文链接:https://www.haomeiwen.com/subject/jzelgctx.html