• LeetCode 2000. Reverse Prefix of Word


    Given a 0-indexed string word and a character chreverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.

    • For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".

    Return the resulting string.

    Example 1:

    Input: word = "abcdefd", ch = "d"
    Output: "dcbaefd"
    Explanation: The first occurrence of "d" is at index 3. 
    Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".
    

    Example 2:

    Input: word = "xyxzxe", ch = "z"
    Output: "zxyxxe"
    Explanation: The first and only occurrence of "z" is at index 3.
    Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".
    

    Example 3:

    Input: word = "abcd", ch = "z"
    Output: "abcd"
    Explanation: "z" does not exist in word.
    You should not do any reverse operation, the resulting string is "abcd".
    

    Constraints:

    • 1 <= word.length <= 250
    • word consists of lowercase English letters.
    • ch is a lowercase English letter.

    就很简单,先找到string里char的位置,然后把这个位置及其之前的string反过来就行了,最后return一个新string。

    纯自己写:

    1. class Solution {
    2. public String reversePrefix(String word, char ch) {
    3. StringBuilder sb = new StringBuilder();
    4. int index = -1;
    5. for (int i = 0; i < word.length(); i++) {
    6. if (word.charAt(i) == ch) {
    7. index = i;
    8. break;
    9. }
    10. }
    11. if (index == -1) {
    12. return word;
    13. }
    14. for (int i = index; i >= 0; i--) {
    15. sb.append(word.charAt(i));
    16. }
    17. for (int i = index + 1; i < word.length(); i++) {
    18. sb.append(word.charAt(i));
    19. }
    20. return sb.toString();
    21. }
    22. }

    看了下solutions还可以纯用java api,巧妙的用了StringBuilder的substring()和reverse()方法:

    1. class Solution {
    2. public String reversePrefix(String word, char ch) {
    3. int index = word.indexOf(ch);
    4. if (index == -1) {
    5. return word;
    6. }
    7. StringBuilder sb = new StringBuilder(word.substring(0, index + 1)).reverse();
    8. return sb.append(word.substring(index + 1, word.length())).toString();
    9. }
    10. }

  • 相关阅读:
    Spring注解(简便地使用 Bean )
    太阳能路灯的根本结构及作业原理
    知识点滴 - 关于头文件的重复包含问题
    Kubernetes简介
    免费的百度官网认证怎么搞?什么单位官网认证免费?
    数据仓库与数据挖掘实验练习题
    Spring Cloud Gateway 服务网关的部署与使用详细介绍
    如何在10亿级别用户中检查用户名是否存在?
    【教3妹学编程-java基础6】详解父子类变量、代码块、构造函数执行顺序
    过午不食有依据吗
  • 原文地址:https://blog.csdn.net/qq_37333947/article/details/132623910