recursion moving char to the end of the string

后端 未结 3 1338
我寻月下人不归
我寻月下人不归 2021-01-24 15:04

i need to get a string and rearrange it with recursion by getting char and by that char i have to move that char everywhere on the string to the end like \"Hello world!\" ,\'l\

3条回答
  •  余生分开走
    2021-01-24 15:35

    If you use recursion, it will be pretty expensive call for the result you are expecting. Lot of movement of String or charArray elements, eitherway you do. I don't see its a wiser choice. I would do it this way, it will be of space complexity O(2n) & performance complexity O(n).

    public class Solve {
    public static void main(String[] args) {
        System.out.println(ChToLast("Hello world!", 'l'));
    }
    
    public static String ChToLast(String str, char ch) {
        char[] chars = str.toCharArray();
        char[] modChars = new char[chars.length];
        int i = 0;      
        for(char element : chars){
            if(ch != element){
                modChars[i++] = element;
            }
        }
        Arrays.fill(modChars, i, chars.length , ch);
        return new String(modChars);
    }   
    }
    

提交回复
热议问题