首页 > 其他分享 >leetcode 344. Reverse String

leetcode 344. Reverse String

时间:2023-05-30 18:04:50浏览次数:42  
标签:return String int bytes public 344 byte leetcode

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

class Solution(object):
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        return s[::-1]

其他解法:

public class Solution {
    public String reverseString(String s) {
        byte[] bytes = s.getBytes();
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            bytes[i] = (byte) (bytes[i] ^ bytes[j]);
            bytes[j] = (byte) (bytes[i] ^ bytes[j]);
            bytes[i] = (byte) (bytes[i] ^ bytes[j]);
            i++;
            j--;
        }
        return new String(bytes);
    }
}

用到了交换不用任何空间。

public class Solution {
    public String reverseString(String s) {
        byte[] bytes = s.getBytes();
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            byte temp = bytes[i];
            bytes[i] = bytes[j];
            bytes[j] = temp;
            i++;
            j--;
        }
        return new String(bytes);
    }
}
class Solution {
public:
    string reverseString(string s) {
        int i = 0, j = s.size() - 1;
        while(i < j){
            swap(s[i++], s[j--]); 
        }
        
        return s;
    }
};

 

标签:return,String,int,bytes,public,344,byte,leetcode
From: https://blog.51cto.com/u_11908275/6381147

相关文章

  • leetcode 557. Reverse Words in a String III
    Givenastring,youneedtoreversetheorderofcharactersineachwordwithinasentencewhilestillpreservingwhitespaceandinitialwordorder.Example1:Input:"Let'stakeLeetCodecontest"Output:"s'teLekatedoCteeLtsetno......
  • leetcode 476. Number Complement
    Givenapositiveinteger,outputitscomplementnumber.Thecomplementstrategyistoflipthebitsofitsbinaryrepresentation.Note:Thegivenintegerisguaranteedtofitwithintherangeofa32-bitsignedinteger.Youcouldassumenoleadingzerobiti......
  • leetcode 561. Array Partition I
    Givenanarrayof2nintegers,yourtaskistogrouptheseintegersintonpairsofinteger,say(a1,b1),(a2,b2),...,(an,bn)whichmakessumofmin(ai,bi)forallifrom1tonaslargeaspossible.Example1:Input:[1,4,3,2]Output:4Explanation:......
  • leetcode 728. Self Dividing Numbers
    Aself-dividingnumberisanumberthatisdivisiblebyeverydigititcontains.Forexample,128isaself-dividingnumberbecause128%1==0,128%2==0,and128%8==0.Also,aself-dividingnumberisnotallowedtocontainthedigitzero.Givenal......
  • leetcode 657. Judge Route Circle
    Initially,thereisaRobotatposition(0,0).Givenasequenceofitsmoves,judgeifthisrobotmakesacircle,whichmeansitmovesbackto theoriginalplace.Themovesequenceisrepresentedbyastring.Andeachmoveisrepresentbyacharacter.The......
  • leetcode 461. Hamming Distance
    The Hammingdistance betweentwointegersisthenumberofpositionsatwhichthecorrespondingbitsaredifferent.Giventwointegers x and y,calculatetheHammingdistance.Note:0≤ x, y <231.Example:Input:x=1,y=4Output:2Explanation:1......
  • leetcode 771. Jewels and Stones
    You'regivenstrings J representingthetypesofstonesthatarejewels,and S representingthestonesyouhave. Eachcharacterin Sisatypeofstoneyouhave. Youwanttoknowhowmanyofthestonesyouhavearealsojewels.Thelettersin J areg......
  • leetcode 378. Kth Smallest Element in a Sorted Matrix
    Givenanxnmatrixwhereeachoftherowsandcolumnsaresortedinascendingorder,findthekthsmallestelementinthematrix.Notethatitisthekthsmallestelementinthesortedorder,notthekthdistinctelement.Example:matrix=[[1,5,9......
  • leetcode 617. Merge Two Binary Trees
    Giventwobinarytreesandimaginethatwhenyouputoneofthemtocovertheother,somenodesofthetwotreesareoverlappedwhiletheothersarenot.Youneedtomergethemintoanewbinarytree.Themergeruleisthatiftwonodesoverlap,thensumn......
  • leetcode 257. Binary Tree Paths
    Givenabinarytree,returnallroot-to-leafpaths.Forexample,giventhefollowingbinarytree: 1/\23\5Allroot-to-leafpathsare:["1->2->5","1->3"]#Definitionforabinarytreenode.#classTreeNode(obje......