您的位置:首页 > 其它

leetcode(01)

2018-01-06 17:43 183 查看
 一、给定两个字符串A和B,找到A必须重复的最小次数,使得B是它的一个子字符串。 如果没有这样的解决方案,返回-1。

    例如,用A =“abcd”和B =“cdabcdab”。

    返回3,因为通过重复三次("abcdabcdabcd"),B是它的一个子串; 而B不是重复两次的子串("abcdabcd"). 

    注意:A和B的长度在1到1000之间

public static int repeatedStringMatch(String A,String B){
int count=0;
StringBuilder sb=new StringBuilder();
while(sb.length()<B.length()){  //要包含这个子字符串首先长度要>=它
sb.append(A);
count++;
}
if(sb.toString().contains(B)) return count;
if(sb.append(A).toString().contains(B)) return ++count;
return -1;
}
  二、给一个非空字符串s,你可以最多删除一个字符,判断是否可以变成一个回文字符串。

    eg:

    Input: "aba"

    Output: True

   Input: "abca"

   Output: True

   Explanation: You could delete the character 'c'.  

public static boolean validPalindrome(String s){
int a=-1,b=s.length();  //a,b代表检查对应字符是否相同的前后下标
while(++a<--b)
if(s.charAt(a)!=s.charAt(b))
return isPalindromic(s,a,b+1)||isPalindromic(s,a-1,b);
//最多删除的一个可能在左边或者右边,所以中间要或,表示要么在左/右,再进第二个函数直接比较出结果
//因为最多只给一次机会,这里进入了这仅有的一次机会
return true;
}

public static boolean isPalindromic(String s, int a, int b) {
while(++a<--b)
if(s.charAt(a)!=s.charAt(b))
return false;
return true;
}
  三、最初,位置(0,0)处有一个机器人。 给出它的一系列动作,判断这个机器人是否有一个圆圈,这意味着它回到原来的位置。移动顺序由一个字符串表示。 而每一个动作都是由一个人物来表现的。 有效的机器人移动R(右),L(左),U(上)和D(下)。输出应该是真或假,表示机器人是否成圈。

eg:

  Input:"UD"

  Output:true

  

  Input:"LL"

  Output:false
public static boolean judgeCircle(String moves){
int x=0;
int y=0;
for(char ch:moves.toCharArray()){
if(ch=='U') y++;
if(ch=='D') y--;
if(ch=='R') x++;
if(ch=='L') x--;
}
return y==0&&x==0;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: