warmup2

Given a string, return true if the first instance of “x” in the string is immediately followed by another “x”.

doubleX(“axxbb”) → true
doubleX(“axaxax”) → false
doubleX(“xxxxx”) → true
indexOf()定位子字符串在字符串首次出现位置
startsWith()是否以子字符串开头,return true or false

boolean doubleX(String str) {
  int i=0;
  str+="x";
  while(str.charAt(i)!='x'){i++;}
  if(i<str.length()-2 && str.charAt(i+1)=='x') return true;
  else return false;
}
/*****************************************************/
boolean doubleX(String str) {
  int i = str.indexOf("x");
  if (i == -1) return false; // no "x" at all

  // Is char at i+1 also an "x"?
  if (i+1 >= str.length()) return false; // check i+1 in bounds?
  return str.substring(i+1, i+2).equals("x");

  // Another approach -- .startsWith() simplifies the logic
  // String x = str.substring(i);
  // return x.startsWith("xx");
}

Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so “hixxxhi” yields 1 (we won’t count the end substring).

last2(“hixxhi”) → 1
last2(“xaxxaxaxx”) → 1
last2(“axxxaaxx”) → 2

public int last2(String str) {
  int n=str.length()-1;
  int count=0;
  if(n>2){
  String last = str.substring(n-1);
  for(int i=0;i<n-1;i++)
    if(str.substring(i).startsWith(last)) count++;
  }
  return count;
}
/********************************************************/
public int last2(String str) {
  // Screen out too-short string case.
  if (str.length() < 2) return 0;

  String end = str.substring(str.length()-2);
  // Note: substring() with 1 value goes through the end of the string
  int count = 0;

  // Check each substring length 2 starting at i
  for (int i=0; i<str.length()-2; i++) {
    String sub = str.substring(i, i+2);
    if (sub.equals(end)) {  // Use .equals() with strings
      count++;
    }
  }

  return count;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值