微软算法100题26 左旋转字符串
生活随笔
收集整理的這篇文章主要介紹了
微软算法100题26 左旋转字符串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
26.左旋轉字符串
題目:
定義字符串的左旋轉操作:把字符串前面的若干個字符移動到字符串的尾部。
如把字符串abcdef 左旋轉2 位得到字符串cdefab。請實現字符串左旋轉的函數。
要求時間對長度為n 的字符串操作的復雜度為O(n),輔助內存為O(1)
?
思路:先反轉整個字符串 -> fedcba 在分別反轉各個子字符串 fedc - ba -> cdef - ab
?
1 package com.rui.microsoft; 2 3 public class Test26_LeftRotateString { 4 5 public static void main(String[] args) { 6 String s = leftRotate("abcdef", 5); 7 System.out.println(s); 8 } 9 10 public static String leftRotate(String s, int from){ 11 StringBuilder sb = new StringBuilder(); 12 13 //reverse all 14 s = reverse(s); 15 16 String s0 = s.substring(0, s.length() - from + 1); 17 String s1 = s.substring(s.length() - from + 1, s.length()); 18 19 //reverse each part 20 sb.append(reverse(s0)).append(reverse(s1)); 21 return sb.toString(); 22 } 23 24 private static String reverse(String s){ 25 char[] as = s.toCharArray(); 26 int i = 0; 27 int j = s.length() - 1; 28 while(i<j){ 29 swap(as, i,j); 30 i++; 31 j--; 32 } 33 return String.copyValueOf(as); 34 } 35 36 private static void swap(char[] a, int i, int j){ 37 char temp = a[i]; 38 a[i] = a[j]; 39 a[j] = temp; 40 } 41 }?
轉載于:https://www.cnblogs.com/aalex/p/4911042.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的微软算法100题26 左旋转字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux基础学习7
- 下一篇: 0基础学习ios开发笔记第二天