【Leetcode】2000. Reverse Prefix of Word

题目地址:

https://leetcode.com/problems/reverse-prefix-of-word/

给定一个字符串 s s s和一个字符 c c c,要求将 s s s中第一次出现 c c c的位置和之前字符组成的前缀做翻转,返回结果字符串。

代码如下:

public class Solution {
    
    
    public String reversePrefix(String word, char ch) {
    
    
        char[] s = word.toCharArray();
        for (int i = 0; i < s.length; i++) {
    
    
            if (s[i] == ch) {
    
    
                for (int j = 0; j < i; j++, i--) {
    
    
                    char tmp = s[j];
                    s[j] = s[i];
                    s[i] = tmp;
                }
                
                return new String(s);
            }
        }
        
        return word;
    }
}

时空复杂度 O ( l s ) O(l_s) O(ls)

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/121607331