日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

微软算法100题26 左旋转字符串

發(fā)布時間:2025/6/17 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 微软算法100题26 左旋转字符串 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

26.左旋轉(zhuǎn)字符串
題目:
定義字符串的左旋轉(zhuǎn)操作:把字符串前面的若干個字符移動到字符串的尾部。
如把字符串a(chǎn)bcdef 左旋轉(zhuǎn)2 位得到字符串cdefab。請實現(xiàn)字符串左旋轉(zhuǎn)的函數(shù)。
要求時間對長度為n 的字符串操作的復(fù)雜度為O(n),輔助內(nèi)存為O(1)

?

思路:先反轉(zhuǎn)整個字符串 -> fedcba 在分別反轉(zhuǎn)各個子字符串 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 }

?

轉(zhuǎn)載于:https://www.cnblogs.com/aalex/p/4911042.html

《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的微软算法100题26 左旋转字符串的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。