牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def ReverseSentence(self, s): 4 ary = s.split(' ') 5 for i in range(len(ary)): 6 ary[i] = ary[i][::-1] 7 #print(ary[i]) 8 return " ".join(ary)[::-1] 9 # write code here
Java版代码,leetcode地址:
1 class Solution { 2 public String reverseWords(String s) { 3 String[] strs = s.trim().split(" "); // 删除首尾空格,分割字符串 4 StringBuilder res = new StringBuilder(); 5 for(int i = strs.length - 1; i >= 0; i--) { // 倒序遍历单词列表 6 if(strs[i].equals("")) continue; // 遇到空单词则跳过 7 res.append(strs[i] + " "); // 将单词拼接至 StringBuilder 8 } 9 return res.toString().trim(); // 转化为字符串,删除尾部空格,并返回 10 } 11 }
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def LeftRotateString(self, s, n): 4 lens = len(s) 5 if lens == 0: 6 return '' 7 if n > lens: 8 n = n % lens 9 t = s[n:] + s[:n] 10 return t 11 # write code here
Java版代码,leetcode地址:
1 class Solution { 2 public String reverseLeftWords(String s, int n) { 3 int lens = s.length(); 4 if (lens == 0) { 5 return ""; 6 } 7 if (lens > n) { 8 n = n % lens; 9 } 10 char[] chars = s.toCharArray(); 11 char[] chars1 = Arrays.copyOfRange(chars, 0, n); 12 char[] chars2 = Arrays.copyOfRange(chars, n, lens); 13 14 String part2 = new String(chars2); 15 StringBuilder sResultString = new StringBuilder(part2); 16 for(Character c : chars1) { 17 String cString = c.toString(); 18 sResultString.append(cString); 19 } 20 return sResultString.toString(); 21 } 22 }