1.编写程序,在原字符串中把字符串尾部的m个字符移动到字符串的头部,要求:长度为n的字符串操作时间复杂度为O(n),空间复杂度为O(1)。 例如,原字符串为”Ilovebaofeng”,m=7,输出结果为:”baofengIlove”。
2、单词翻转。输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变,句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。例如,输入“I am a student.”,则输出“student. a am I”。
代码实现:
package alg; /** * @author zha * 字符串反转 */ public class Alg1StringReserv { public static void main(String[] args) { String test = "ilovebaofeng"; int index = 7 ; String re = reserve(test,index); System.out.println(re); String test2 = "I am a student."; char index2 = ' '; String re2 = reserve(test2,index2); System.out.println(re2); } //根据某一个特定的字符进行翻转 private static String reserve(String test, char index) { char[] chars = test.toCharArray(); int from = 0,to = 0; for (int i = 0; i < chars.length; i++) { char temp = chars[i]; if(temp == index){ to = i-1; turnOver(chars,from,to); from = i+1; } } if(to < chars.length - 1){ turnOver(chars, from, chars.length-1); } turnOver(chars,0,chars.length-1); return new String(chars); } private static String reserve(String test, int index) { int length = test.length(); int begine = (length - index - 1)%length; char[] chars = test.toCharArray(); turnOver(chars,0,begine); turnOver(chars,begine+1,length-1); turnOver(chars,0,length-1); return new String(chars); } private static void turnOver(char[] chars, int begine, int to) { if(begine < to){ for (; begine < to; begine++,to--) { swap(chars,begine,to); } } } private static void swap(char[] chars, int begine, int to) { char temp = chars[begine]; chars[begine] = chars[to]; chars[to] = temp; } }
欢҉迎҉指҉出҉代҉码҉中҉不҉足҉的҉地҉方҉。