LintCode——旋转字符串

描述:给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)

样例:对于字符串 "abcdefg"  

     offset=0 => "abcdefg"

     offset=1 => "gabcdef"

     offset=2 => "fgabcde"

     offset=3 => "efgabcd"

1、Python

 1 class Solution:
 2     """
 3     @param str: An array of char
 4     @param offset: An integer
 5     @return: nothing
 6     """
 7     def rotateString(self, str, offset):
 8         # write your code here
 9         if not offset: return   #无偏移量
10         if not str: return      #字符串是空串
11     
12         offset = offset % len(str)
13         for i in range(offset): #字符串旋转
14             c = str.pop()
15             str.insert(0,c)
16         return str

2、Java

 1 public class Solution {
 2     /**
 3      * @param str: An array of char
 4      * @param offset: An integer
 5      * @return: nothing
 6      */
 7     public void rotateString(char[] str, int offset) {
 8         // write your code here
 9         char temp;
10         if(offset == 0) return;     //偏移量为0
11         if(str.length == 0) return; //字符串为空串
12         
13         
14         int len=str.length;
15         for(int i = 1;i <= offset % len;i++){
16             temp = str[len - 1];
17             int j = len - 2;
18             while(j >= 0){
19                 str[j + 1] = str[j];
20                 j--;
21             }
22             str[0]=temp;
23         }
24     }
25 }

猜你喜欢

转载自www.cnblogs.com/wangcj2015/p/9112295.html
今日推荐