翻转单词面试常考题

Posted 赵jc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了翻转单词面试常考题相关的知识,希望对你有一定的参考价值。

翻转单词面试常考题

反转字符串

class Solution 
    public void reverseString(char[] s) 
         if(s == null || s.length == 0) 
            return ;
        
        int i = 0, j = s.length - 1;
        while(i < j) 
            char tmp = s[i];
            s[i] = s[j];
            s[j] = tmp;
            i++;
            j--;
        
        return ;
    

反转字符串II(反转k个)

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

class Solution 
    public String reverseStr(String s, int k) 
        char[] a = s.toCharArray();
        for (int start = 0; start < a.length; start += 2 * k) 
            int i = start, j = Math.min(start + k - 1, a.length - 1);
            while (i < j) 
                char tmp = a[i];
                a[i++] = a[j];
                a[j--] = tmp;
            
        
        return new String(a);
    

仅仅反转字母

https://leetcode-cn.com/problems/reverse-only-letters/

class Solution 
   public String reverseOnlyLetters(String S) 
        StringBuilder ret = new StringBuilder();
        int j = S.length() - 1;
        for (int i = 0; i < S.length(); ++i) 
            if (Character.isLetter(S.charAt(i))) 
                while (!Character.isLetter(S.charAt(j)))
                    j--;
                ret.append(S.charAt(j--));
             else 
                ret.append(S.charAt(i));
            
        
        return ret.toString();
    

反转单词(顺序改变)

https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/

class Solution 
    public String reverseWords(String s) 
        int j = s.length() - 1, i = j;
        StringBuffer ret = new StringBuffer();
        while(i >= 0) 
            while(i >= 0 && s.charAt(i) != ' ') 
                i--;
            
            ret.append(s.substring(i + 1, j + 1) + " ");
            while(i >= 0 && s.charAt(i) == ' ') 
                i--;
            
            j = i;
        
        return ret.toString().trim();
    

反转单词(顺序不变)

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

class Solution 
    public String reverseWords(String s) 
        String[] strs = s.split(" ");
	    StringBuffer ret = new StringBuffer();
	    for (int i = 0; i < strs.length; i++) 
		    ret.append(new StringBuffer(strs[i]).reverse().toString());
		    ret.append(" ");
	    
	    return ret.toString().trim();
    

以上是关于翻转单词面试常考题的主要内容,如果未能解决你的问题,请参考以下文章

IC面试常考题 Verilog三分频电路设计(占空比50%,三分之一,三分之二)

IC面试常考题 Verilog三分频电路设计(占空比50%,三分之一,三分之二)

C++入门—namespace的使用傻傻分不清楚&C++中函数的参数也可以配备胎&面试常考题

python面试总结2(函数常考题和异常处理)

回溯面试常考题

LeetCode面试常考题:Two Sum